I am new to the Django web framework.
I have a template that displays the list of all objects. I have all the individual objects listed as a link (object title), clicking on which I want to redirect to another page that shows the object details for that particular object.
I am able to list the objects but not able to forward the object/object id to the next template to display the details.
views.py
def list(request):
listings = listing.objects.all()
return render_to_response('/../templates/listings.html',{'listings':listings})
def detail(request, id):
#listing = listing.objects.filter(owner__vinumber__exact=vinumber)
return render_to_response('/../templates/listing_detail.html')
and templates as:
list.html
{% for listing in object_list %}
<!--<li> {{ listing.title }} </li>-->
<a href="{{ listing.id }}">{{ listing.title}}</a><br>
{% endfor %}
detail.html
{{ id }}
The variables that you pass in the dictionary of
render_to_responseare the variables that end up in the template. So indetail, you need to add something like{'listing': MyModel.objects.get(id=vinumber)}, and then the template should say{{ listing.id }}. But hat’ll crash if the ID doesn’t exist, so it’s better to useget_object_or_404.Also, your template loops over
object_listbut the view passes inlistings— one of those must be different than what you said if it’s currently working….Also, you should be using the
{% url %}tag and/orget_absolute_urlon your models: rather than directly sayinghref="{{ listing.id }}", say something likehref="{% url listing-details listing.id %}", wherelisting-detailsis the name of the view inurls.py. Better yet is to add aget_absolute_urlfunction to your model with thepermalinkdecorator; then you can just sayhref="{{ listing.get_absolute_url }}", which makes it easier to change your URL structure to look nicer or use some attribute other than the database id in it.