【问题标题】:Django template: access query_set and non-query_set results in same templateDjango 模板:在同一模板中访问 query_set 和 non-query_set 结果
【发布时间】:2013-11-15 13:59:47
【问题描述】:

我有一个 Django 应用程序,其中包含有关学校和州的信息。我希望我的模板显示每个州的学校列表以及基于 URL 中的 state 参数的州名称。因此,如果用户访问 example.com/vermont/,他们将看到佛蒙特州学校的列表和一个标签,表明他们在“佛蒙特州”页面上。我可以得到每个州的学校列表来工作,但我不知道如何简单地在 h1 标签中列出州名。

这是我的 models.py

from django.db import models

class School(models.Model):
school_name    = models.CharField(max_length=200)
location_state = models.CharField(max_length=20)

def __unicode__(self):
    return self.school_name

这是我的 views.py

from django.views.generic import ListView

class StateListView(ListView):
    model = School
    template_name = 'state.html'
    context_object_name = 'schools_by_state'

    def get_queryset(self):
        state_list = self.kwargs['location_state']
        return School.objects.filter(location_state=state_list)

这是我的 state.html 模板:

{% extends 'base.html' %}

{% block content %}
    <h1>{{school.location_state }}</h1> [THIS IS THE LINE THAT DOES NOT WORK]

    {% for school in schools_by_state %}
    <ul>
        <li>{{ school.school_name }}</li>
    </ul>
    {% endfor %}
{% endblock content %}

我在这里错过了什么?

【问题讨论】:

  • 我认为您需要在 forloop 中移动 &lt;h1&gt; 标签,那么这应该可以工作 &lt;h1&gt;{{ school.location_state }}&lt;/h1&gt; 或者如果您只想显示第一所学校的一个状态,那么您可以这样做 &lt;h1&gt;{{ schools_by_state.0.location_state }}&lt;/h1&gt;??
  • 是的,有效!谢谢阿米尔。我只想显示一个状态,所以我使用了:

    {{schools_by_state.0.location_state }}

  • @jbub 答案很好。你应该遵循这一点。

标签: python django django-templates django-queryset


【解决方案1】:

问题是学校变量从不进入上下文。您只是将schools_by_state 设置为上下文。

要添加一些额外的上下文,您需要覆盖 get_context_data 方法。这样您就可以从 url 参数中添加 location_state:

def get_context_data(self, **kwargs):
    context = super(StateListView, self).get_context_data(**kwargs)
    context.update({'state': self.kwargs['location_state']})
    return context

然后您可以在模板中使用{{ state }} 而不是{{ school.location_state }}

【讨论】:

  • 感谢@jbub 的回复和解释。非常感谢。
猜你喜欢
  • 2017-07-17
  • 2017-10-07
  • 2011-10-04
  • 2012-09-06
  • 2016-01-17
  • 2012-08-10
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
相关资源
最近更新 更多