我有一个 Django 应用程序,其中包含有关学校和州的信息。我希望我的模板显示每个州的学校列表,以及基于 URL 中的州参数的州名称。因此,如果用户访问 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 %}
我在这里缺少什么?
最佳答案
问题是 school 变量永远不会进入上下文。您只需将 school_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 }}
。
关于python - Django 模板 : access query_set and non-query_set results in same template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776388/