繁体   English   中英

Django,在视图中排除上下文处理器

[英]Django, exclude a context processor in a view

我有一个带有菜单的网站。 要生成菜单,我需要在数据库中进行一些查询。 因此,我创建了一个上下文处理器以在所有视图中进行操作。

我的某些观点实际上是形式。 当用户单击某些按钮时,我使用ajax获取它们,并使用jquery ui对话框显示它们。

对于那些非常复杂的形式,我无法删除所有上下文处理器,尤其需要auth,static和il8n上下文处理器。 但是我不想在数据库中进行基于菜单的查询来显示这些表格。

有没有办法在视图中排除上下文处理器? 我试图在视图的“ request.session”中放入一个变量,然后将其删除并在上下文处理器中返回一个空字典。 但这很糟糕,并且可能存在并发问题。 我还可以在上下文处理器中的“请求”中解析网址,然后返回一个空字典,但这听起来又像是一种黑客。

有什么想法或建议吗? 谢谢,

这就是Django的惰性对象的用途。 您无需提供上下文处理器中的实际内容,而可以为惰性对象提供关联的功能。 当实际尝试使用该对象的对象(例如在模板中)时,它将调用该函数。 这个答案给出了相同问题的例子。

如果多次使用该变量,请务必小心;否则请注意。 一些选项将重新调用该函数,而另一些选项将保存结果。 您可以肯定一下来源 我认为SimpleLazyObject (如上面的答案所示) SimpleLazyObject您的要求,但是我最近没有足够肯定地使用它。

(应要求提供答案...。)

你可以继承RequestContextdjango.template.context并重新定义其__init__方法。 然后,您可以在那些特定的视图中使用经过修改的RequestContext RequestContext__init__当前看起来像这样:

def __init__(self, request, dict=None, processors=None, current_app=None, use_l10n=None):
        Context.__init__(self, dict, current_app=current_app, use_l10n=use_l10n)
        if processors is None:
            processors = ()
        else:
            processors = tuple(processors)
        for processor in get_standard_processors() + processors:
            self.update(processor(request))

在这里, get_standard_processors()返回设置中定义的上下文处理器。 在调用上下文处理器之前(上面代码的最后一行),您可以添加检查以确定是否需要使用哪些处理器,以及需要跳过哪些处理器。

重新设计您的应用程序可能会更容易,以便某些视图进行此查询,而其他视图则不会。 您可以通过编写一个“基于类的视图”来进行此特定数据库查询,并将其添加到上下文中,然后在需要新视图进行该额外查询时继承它,从而避免这种重复。 我主张使用这种方法,而不要使用全局上下文处理器。

本示例说明如何向默认模板上下文添加内容。

使用各种模板引擎非常容易实现。

1.在项目设置中定义替代(轻型)模板引擎

TEMPLATES = [
    # The default engine - a heavy one with a lot of context processors
    {
        'NAME': 'default',
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                'django.template.context_processors.request',
                'django.template.context_processors.media',
                'django.template.context_processors.static',

                'some_app_1.context_processors.very_heavy_cp_1',
                'some_app_2.context_processors.very_heavy_cp_2',
                'some_app_3.context_processors.very_heavy_cp_3',
            ],
            'debug': True,
        },
    },
    # Light engine - only very necessary things go here
    {
        'NAME': 'light',
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.i18n',
                'django.template.context_processors.request',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
            ],
            'debug': True,
        },
    },
]

2.如何在您的视图中使用光引擎

some_app_1.views.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import View, TemplateView

样品灯视图:

class TestLightView(View):
    """Test light view."""

    template_name = 'some_app_1/test_light_view.html'

    def get(self, request):
        context = {}
        response = render_to_response(
            self.template_name,
            context,
            context_instance=RequestContext(request),
            using='light'  # Note, that we use `light` engine here
        )
        return response

样本普通(重)视图:

class TestNormalView(View):
    """Test normal view."""

    template_name = 'some_app_1/test_normal_view.html'

    def get(self, request):
        context = {}
        response = render_to_response(
            self.template_name,
            context,
            context_instance=RequestContext(request),
            using='default'  # Note, that we use `default` engine here
        )
        return response

如果使用TemplateView ,请定义template_engine属性。

样品灯视图:

class TestTemplateLightView(TemplateView):
    """Test template light view"""

    template_engine = 'light'  # Note, that we use `light` engine here

    # Your code goes here

样本普通(重)视图:

class TestTemplateNormalView(TemplateView):
    """Test template normal view."""

    template_engine = 'default'  # Note, that we use `default` engine here

    # Your code goes here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM