1

I have a Django app that contains info on schools and states. I want my template to display a list of schools per state and also the name of the state based on the state parameter in the URL. So if a user goes to example.com/vermont/ they will see a list of Vermont schools and a tag that says they're on the "Vermont" page. I can get the list of schools per state to work, but I can't figure out how to simply list the state name in the h1 tag.

Here is my 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

Here is my 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)

And here's my template for 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 %}

What am I missing here?

4

1 に答える 1

1

問題は、学校変数がコンテキストに入らないことです。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 }}

于 2013-11-04T20:32:32.563 に答える