如何将多个对象作为上下文传递给 Django 中基于 class 的通用视图中的模板?

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

我需要将两个不同的对象传递给我的模板,我尝试传递但它只显示一个。

我试图将它作为字典传递,但我卡住了,然后我选择了这种方法,它也导致只从第一个对象获取数据。

在我使用的模板标签中

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 %}

我需要显示来自两个模型(TestUser 和 Vechile)的数据,现在我只从 TestUser 模型获取数据。

您可以通过在 return context 之前的视图中添加 print(context) 或使用 django-debug-toolbar 来调试它。您将看到上下文包含 object_listvechile.

因此,在模板中,您可以:

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

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