簡體   English   中英

Django上下文處理器不會在模板中顯示新的上下文值

[英]Django context processor doesn't display new context values in template

編輯:現在更新,我將問題范圍縮小到上下文處理器變量,該變量不適用於使用自定義標記加載的模板。

我正在使用Django 1.11,這是我第一次嘗試使用自定義上下文處理器。

問題是應該從上下文處理器添加的上下文變量不會從自定義標簽加載的模板中返回任何內容。 我沒有收到任何錯誤。

因此,在{{testcontext}}下面應返回“ IT WORKED!”。 並在我的base.html模板中執行此操作,但是在加載@ register.inclusion_tag()的模板中不返回任何內容。

settings.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',
                'appname.context_processors.test_context',
            ],
        },
    },
]

context_processors.py:

def test_context(request):
    return {'testcontext': 'TEST WORKED!'}

tags.py

from django import template

from appname.models import Category

register = template.Library()

@register.inclusion_tag('template.html')
def load_category(selected_slug=None):
    return {
        'categories': Category.objects.all(),
        'selected':selected_slug,
    }

views.py:

from django.views.generic import ListView
from appname.models import MyModel

class MyView(ListView):
    model = MyModel

urls.py

from django.conf.urls import url

from appname.views import MyView

urlpatterns = [
    url(r'^$', MyView.as_view(), name="home"),
]

template.html

{{ testcontext }}

因此,問題出在我的自定義標記中,當加載template.html時,該標記未保留上下文。 因此,以下代碼對其進行了修復,並且上下文處理器中的我的變量現在可以按預期運行。

tags.py

from django import template

from appname.models import Category

register = template.Library()

@register.inclusion_tag('template.html', takes_context=True)
def load_category(context,selected_slug=None):
    return {
        'categories': Category.objects.all(),
        'selected': selected_slug,
        'testcontext': context['testcontext'] 
    }

暫無
暫無

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

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