简体   繁体   中英

Django template: access query_set and non-query_set results in same template

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?

The problem is that the school variable never enters the context. You are only setting the schools_by_state to the context.

To add some extra context you need to override the get_context_data method. This way you can add the location_state from the url parameter:

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

Then you can use the {{ state }} instead of {{ school.location_state }} in your template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM