[Fixed]-Sort children into parent in django template

1πŸ‘

βœ…

I think you want to use a DetailView representing the state, rather that a list of cities. This because your URL represents a state’s object view.

So, you can

class CityInStateView(generic.DetailView):
    model = State
    template_name = 'template.html'
    slug_field = 'state_slug'

    def get_context_data(self, **kwargs):
        context = super(CityInStateView, self).get_context_data(**kwargs)
        context['state'] = self.object
        context['city_list'] = self.object.city_set.all().order_by('city_name')
        return context

and then your template (simplified example) would be as simple as:

<h1>{{ state.state_name }}</h1>
{% for city in city_list %}
  <p>{{ city.city_name }}</p>
{% endfor %}

For the URL to work with DetailView, and because you did not use slug as the field name, you need to tell the DetailView that state_slug is your slug. You may want to add unique=True to your model.

Hope you can take it from here

πŸ‘€dkarchmer

Leave a comment