我正在为学校网站制作一个django项目
我有一个base.html作为子模板的父模板,它是每个页面的内容
base.html包含一个带有学校徽标的导航栏和一个标题为“单元”的部分
这是呈现讲师页面的代码
views.朋友 . .
def lecturer_home(request):
user = request.user
query for the user first name and full name
query for the units that the user is teaching and their teaching
period in unit_list and period_display
class_display = zip(unit_list, period_display)
user_dict = {
'f_name' : user.first_name,
'fl_name' : user.first_name + ' ' + user.last_name,
'class_display' : class_display,
}
return render(request, 'Lecturer/lecturerdashboard.html', user_dict)
else:
return HttpResponse('Unexpected error')
lecturerdashboard.html扩展了base.html
我为views.py添加了较少的代码,因为我认为我没有犯任何错误。我要向大家证实的是,我传递给deskrdashboard.html的user_dict也可以在base.html中使用,但令人困惑的是我发现如果在任何一个中使用了键和值,则另一个不能使用它。例如,我可以在讲话单板的内容部分显示单元,但是当我使用base.html中的class_display在讲师单击“单位”时将单位显示为下拉菜单选项时,内容部分将无效,因为它不理解class_display。抱歉,如果问题在摘要中令人困惑,父母和孩子理解视图传递的参数,但是如果在父母中使用了一个键值,那么孩子不理解它我只是想确认,这是真的吗?谢谢
这与模板没有任何关系。 zip
是一个迭代器。一旦遍历它,它就会耗尽,并且不能再次使用。如果你想多次迭代它,请在上面调用list
:
class_display = list(zip(unit_list, period_display))
我不知道我是否理解清楚:你想要在每个模板中访问一些变量,比如class_display吗?如果是这样,最好的解决方案是使用Context Processors。例:
from users.models import UserMessage
def notifications(request):
if not request.user.is_anonymous:
notifications = UserMessage.objects.filter(
receiver=request.user, read=False)
ctx = {
"notifications": notifications,
"notifications_number": notifications.count()
}
return ctx
return {}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'app_name.context_processors.notifications' # added this!
],
},
},
]