问题
I want to use the same template to view information about each of my database objects. I would like to be able to click on each element in the list and have it link me to a page with info about it. I'm thinking there's an easier way than making a view for each unique object.
I'm listing all of my database objects on my list.html like this:
{% for instance in object_info %}
<li><a href="object">{{ instance.name }}</a></li>
{% endfor %}
My views.py has this view:
def object_view(request):
data = Object.objects.filter(name="")
context={
'object_info':data
}
return render(request, "object.html", context)
Can I pass each {{ instance.name }} to the view and use that as a variable for my filter?
回答1:
Okay first off never do this:
data = Object.objects.filter(name="")
Django has an all() function that will return all objects:
data = Object.objects.all()
Secondly, I hope object_view, data, object_info, object.html are not your actual variable names! If so, please make sure they are meaningful to your application.
Okay back to your problem. Well, you don't need to make a view for every single object. I am assuming that <a href="object">...</a> should refer to a new page that will be populated with the selected object.
If so, you would want to have urls in the <a> tags like this: /objects/object_id/.
This new url needs to be defined like this in urls.py:
urlpatterns += [
url(r'^objects/(?P<oid>[0-9]+)/$', views.object_specific_view, name='objects'),
]
Note the oid url argument. We will be using it to access our specific object.
Now your original template, list.html, should look like:
{% for instance in object_info %}
<li><a href="{% url 'objects' oid = instance.id %}">instance.name</a></li>
{% endfor %}
Where we supply instance.id to oid url argument to produce something like objects/1/ or objects/2/ etc.
Now, this means that you will only need to create one more view with another template.
Your second view object_specific_view:
def object_specific_view(request, oid): # The url argument oid is automatically supplied by Django as we defined it carefully in our urls.py
object = Object.objects.filter(id=oid).first()
context={
'object':object
}
return render(request, "specific_object.html", context)
Now you just need to design your specific_object.html and access the object instance to show details of a specific object :).
来源:https://stackoverflow.com/questions/41080955/django-passing-object-from-template-to-views