[Django]-Django: Passing object from template to views

9👍

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 :).

Leave a comment