Saran Prasad
Saran Prasad

Reputation: 165

How to pass multiple objects as context to templates in class based generic view in django?

I need to pass two different objects to my template,I tried to pass but it showing only one.

I tried to pass it as dict but i got stuck, then i choose this method which also results in getting only the data from the first object.

In template tag i used

views.py

class ShowTable(ListView):
    model = TestUser

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)    
        context['vechile'] = Vechile.objects.all()
        return context

testuser_list.html

 {% for comment in object_list %}
        <tr>
            <td>{{ comment.name }}</td>
            <td>{{ comment.address }}</td>
            <td>{{ comment.phone }}</td>
            <td><a href="{% url 'myapp:edit-table' comment.id %}">edit</a></td>
            <td><a href="{% url 'myapp:delete-table' comment.id %}">Delete</a></td>
        </tr>
    {% endfor %}

 {% for comment in object_list %}
            <tr>
                <td>{{ comment.name }}</td>
                <td>{{ comment.bike }}</td>
                <td>{{ comment.car }}</td>
            </tr>
        {% endfor %}

I need to display data from both the models(TestUser and Vechile), Now i'm getting data from TestUser model only.

Upvotes: 1

Views: 3687

Answers (1)

Alasdair
Alasdair

Reputation: 308839

You can debug this by adding print(context) to the view before return context, or by using the django-debug-toolbar. You will see that the context contains object_list and vechile.

Therefore, in the template, you can do:

{% for object in object_list %}
    {{ object }}
{% endfor %}

{% for v in vechile %}
    {{ v }}
{% endfor %}

Upvotes: 2

Related Questions