簡體   English   中英

Django模板:在同一模板中訪問query_set和non-query_set結果

[英]Django template: access query_set and non-query_set results in same template

我有一個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 %}

我在這里想念什么?

問題在於學校變量從不進入上下文。 您僅將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 }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM