【发布时间】: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 中移动
<h1>标签,那么这应该可以工作<h1>{{ school.location_state }}</h1>或者如果您只想显示第一所学校的一个状态,那么您可以这样做<h1>{{ schools_by_state.0.location_state }}</h1>?? -
是的,有效!谢谢阿米尔。我只想显示一个状态,所以我使用了:
{{schools_by_state.0.location_state }}
-
@jbub 答案很好。你应该遵循这一点。
标签: python django django-templates django-queryset