【问题标题】:Django context error in extended template called by view视图调用的扩展模板中的 Django 上下文错误
【发布时间】:2017-09-25 13:59:28
【问题描述】:

我正在使用 Django-Jet 模板在 Django 1.11 中工作。

现在我需要扩展模板以显示从视图中检索到的一些数据。所以,我定义了我的模板和我的视图。 代码如下:

views.py

from django.shortcuts import render
from django.shortcuts import render_to_response 
from django.views.generic import View  
from django.template.context import RequestContext
from django.template import Context, Template 

class MyView(View):
    def get(self, request, *args, **kwargs):
        op = str(self.kwargs['op']).strip().lower()
        pk = self.kwargs['pk']

        if op =='get':
            template='frontend/templates/show_my_data.html'
            return render_to_response(template,{'foo':'bar'})

        else:
            return HttpResponse("Not found")

我的简单模板:

{% extends "admin/base.html" %}
{% load i18n admin_urls static admin_modify %}
{% block content %}
{{ foo }}
{% endblock %}

settings.py

TEMPLATES = [
{
     'BACKEND': 'django.template.backends.django.DjangoTemplates',
     'DIRS': [os.path.join(BASE_DIR,'static/')],
     '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',
            ],
        },
    },
]

....

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

但是当我运行测试时,我得到一个关键错误:

Request Method:     GET
Request URL:    http://127.0.0.1:8000/admin/data_from_db/get/24/
Django Version:     1.11.2
Exception Type:     KeyError
Exception Value:    

'user'

Exception Location:     /home/marco/sviluppo/myapp/myvenv/lib/python3.4/site-packages/django/template/context.py in __getitem__, line 87
Python Executable:  /home/marco/sviluppo/myapp/myvenv/bin/python 

所以,我做了一些测试,发现问题(可能)出在上下文变量中。这是我需要扩展的基本模板:

base.html

.....
{% if user.is_active and user.is_staff %}
     {% jet_get_menu as app_list %}
            {% if SIDE_MENU_COMPACT %}
                 {% for app in app_list %}
                   #print menu
                 {% endfor%}
.........

如果我删除第一个条件:{% if user.is_active and user.is_staff %},{% jet_get_menu as app_list %} 中会出现 KeyError。 我给你看一些屏幕。

普通管理模板:

https://imgur.com/TKmc1mH

如果我不从 base.html 模板中删除 {% if user.is_active 和 user.is_staff %} 则查看结果

https://imgur.com/BYtnEqM

你可以看到页面完全是空的:没有菜单标签,右上角没有登录框,ecc。

好像没有user这样的上下文变量,但我不明白为什么。

【问题讨论】:

  • 请注意,'DIRS': [os.path.join(BASE_DIR,'static/')], 看起来不对——静态文件和 Django 模板是不同的概念,您不应该将模板存储在静态目录中。
  • 那么,我必须将我的模板移动到其他文件夹中吗?
  • 是的,我建议将所有模板移出static 目录。但是,这是一个单独的问题,它不会修复您的 KeyError

标签: python django templates django-views


【解决方案1】:

您需要使用render 快捷方式而不是render_to_response 以便运行上下文处理器。

if op == 'get':
    template = 'frontend/templates/show_my_data.html'
    return render(request, template, {'foo':'bar'})

【讨论】:

    【解决方案2】:

    您需要在每个模板中加载 jet_tags,您将使用它们:

    {% load jet_tags %}
    

    【讨论】:

    • def get_menu_items(context): pinned_apps = PinnedApplication.objects.filter(user=context['user'].pk).values_list('app_label', flat=True) 在 utils.py 是我认为的问题
    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 2015-07-16
    • 2015-03-03
    • 2012-01-30
    • 2022-01-09
    • 2010-11-27
    • 1970-01-01
    相关资源
    最近更新 更多