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?

3
  • I think you need to move the <h1> tag within forloop then this should work <h1>{{ school.location_state }}</h1> or if you want to show just one state of very first school then you can do <h1>{{ schools_by_state.0.location_state }}</h1>?? Commented Nov 4, 2013 at 20:25
  • Yes that worked! Thanks Aamir. I just wanted to show one state so I used: <h1>{{ schools_by_state.0.location_state }}</h1> Commented Nov 4, 2013 at 20:35
  • @jbub answer is good. You should follow that. Commented Nov 4, 2013 at 20:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @jbub for the response and explanation. Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.