为什么将参数传递给父模板会导致子模板无法使用它们

时间:2019-03-27 03:34:59

标签: django parent extends

我正在为学校网站制作django项目

我有一个base.html作为子模板的父模板,这是每个页面的内容

base.html包含一个带有学校徽标的导航栏,并在其上标有“单元”的部分

这是呈现讲师页面的代码

views.py 。

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输入的代码更少,因为我认为我没有犯任何错误。我想向大家确认的是,我在演讲者dashboard.html中传递的user_dict也可以在base.html中使用,但是令人困惑的是,我发现如果在任何一个中使用了键和值,则另一个不能使用它。 。 例如,我能够在演讲者dashboard.html的内容部分中显示单位,但是当演讲者单击“单位”时,当我在base.html中使用class_display将单位显示为下拉菜单选择时,内容部分将无法工作,因为它不理解class_display。 抱歉,如果这个问题令人困惑 总之,父级和子级都可以理解视图传递的参数,但是如果在父级中使用了键值,则子级将无法理解该参数。 我只想确认,这是真的吗? 谢谢

2 个答案:

答案 0 :(得分:0)

我不知道我是否清楚: 您是否想访问每个模板中的某些变量,例如class_display? 如果是这样,最好的解决方案是使用上下文处理器。示例:

  1. 在您的应用中创建文件,例如context_processors.py
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!
            ],
        },
    },
]
  1. 在settings.py中 模板->'context_processors'添加:
deleteDomain()

答案 1 :(得分:0)

这实际上与模板没有任何关系。 zip是一个迭代器。一旦遍历它,它就筋疲力尽,无法再次使用。如果要多次迭代,请对其调用list

 class_display = list(zip(unit_list, period_display))
相关问题