Django模板不获取上下文变量

2024-05-19 00:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我们将Django 2.1用于Speedy Net。我为用户添加了一个管理视图-每个用户的URL都是用户的相同URL,但前缀是"/admin/user"。我使用上下文处理器定义了管理员用户前缀:

def add_admin_user_prefix(request):
    if ((request.user.is_superuser) or (request.user.is_staff)):
        admin_user_prefix = "/admin/user"
    else:
        admin_user_prefix = ""
    return {
        'admin_user_prefix': admin_user_prefix,
    }

但问题是,基本模板和包含的模板看不到这个变量。我在包含模板时不使用only关键字。但是,基本模板和包含的模板在我打印{{ admin_user_prefix }}时不会打印任何内容。前缀是将管理员重定向到特定于管理员的用户URL,而不是常规用户URL。但我查过了,网址是普通网址。在某些情况下,前缀是打印出来的,在我看来,如果它不是一个包含的模板,也不是一个基本模板,它就会被打印出来。问题是什么?如何解决?你知道吗

speedy/core/settings/base.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            str(APP_DIR / 'templates'),
            str(ROOT_DIR / 'speedy/core/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',
                'django.template.context_processors.i18n',

                'speedy.core.base.context_processors.active_url_name',
                'speedy.core.base.context_processors.settings',
                'speedy.core.base.context_processors.sites',
                'speedy.core.base.context_processors.speedy_net_domain',
                'speedy.core.base.context_processors.speedy_match_domain',
                'speedy.core.base.context_processors.add_admin_user_prefix',
            ],
        },
    },
]

在某些情况下,会打印前缀,因此会创建上下文。我以超级用户和职员的身份查看网站。你知道吗

未打印的模板{{ admin_user_prefix }}包含在include中,例如:

{% include 'admin/user_list_item.html' with user=user %}

或者它们是呈现模板的基本模板({% extends 'profiles/user_base.html' %})。你知道吗

以下是视图:

class UserDetailView(UserMixin, generic.TemplateView):
    template_name = 'profiles/user_detail.html'

    def get_widget_kwargs(self):
        return {
            'request': self.request,
            'user': self.user,
            'viewer': self.request.user,
        }

    def get_widgets(self):
        widgets = []
        for widget_path in django_settings.USER_PROFILE_WIDGETS:
            widget_class = import_string(widget_path)
            widgets.append(widget_class(**self.get_widget_kwargs()))
        return widgets

    def get_context_data(self, **kwargs):
        cd = super().get_context_data(**kwargs)
        cd.update({
            'widgets': self.get_widgets(),
        })
        return cd

profiles/user_detail.html包含{% extends 'profiles/user_detail_base.html' %},其中包含{% extends 'profiles/user_base.html' %},其中包含无法正确显示的{{ admin_user_prefix }}。小部件中的同一个标记显示admin用户前缀。你知道吗

我的模板:

speedy/net/templates/admin/profiles/user_detail.html

{% extends 'profiles/user_detail.html' %}

{% block user_tools %}{% endblock %}

speedy/net/templates/profiles/user_detail.html

{% extends 'profiles/user_detail_base.html' %}

{% load i18n %}

{% block title %}{{ user.name }} / {% block site_title %}{{ block.super }}{% endblock %}{% endblock %}

speedy/core/templates/profiles/user_detail_base.html

{% extends 'profiles/user_base.html' %}

{% load i18n %}

{% block user_content_info %}
    <div class="row flex-wrap">
        {% for widget in widgets %}
            {{ widget.html }}
        {% endfor %}
    </div>
{% endblock %}

speedy/core/templates/profiles/user_base.html

{% extends 'base_site.html' %}

{% load core_tags_and_filters %}
{% load i18n %}
{% load core_messages_tags %}
{% load rules %}

{% block content %}
    {% has_perm 'accounts.view_profile' request.user user as can_view_profile %}
    {% has_perm 'accounts.view_profile_header' request.user user as can_view_profile_header %}
    {% has_perm 'accounts.view_profile_info' request.user user as can_view_profile_info %}

    <div class="row justify-content-center">

        <div class="{% if site == speedy_match %}col-md-7{% else %}col-12{% endif %}">

            {% if can_view_profile_header %}
                <div class="row">
                    <div class="col-md">
                        <div class="page-header">
                            <h1>
                                <a href="{{ admin_user_prefix }}{% url 'profiles:user' slug=user.slug %}">{{ user.name|truncatechars:50 }}</a>{% block user_extra %}{% endblock %}
                            </h1>
                            <div class="text-muted">
                                {% block user_status %}
                                    {% if friendship_request_sent %}
                                        {% trans 'Friendship request sent' %}
                                    {% endif %}
                                    {% if user_is_friend %}
                                        {% trans 'Your friend' context user.get_gender %}
                                    {% endif %}
                                {% endblock %}
                            </div>
                        </div>
                    </div>
                    <div class="col-md-auto">
                        <div class="my-2">
                            {% block user_tools %}
                                {% include 'profiles/tools/tools.html' %}
                            {% endblock %}
                        </div>
                    </div>
                </div>

            {% endif %}

            {% if can_view_profile %}
                {% block user_content %}
                {% endblock %}
            {% else %}
                {% if can_view_profile_info %}
                    {% include 'profiles/block_warning.html' with user=request.user other=user %}
                {% else %}
                    <div class="row">
                        <div class="col-sm-12">
                            <a href="//{{ LANGUAGE_CODE }}.{{ SPEEDY_NET_DOMAIN }}{{ admin_user_prefix }}{% url 'profiles:user' slug=user.slug %}">
                                {# ~~~~ TODO: remove "his/her" and setup strings in Python! #}
                                {% trans "This user doesn't match your profile, " context user.get_gender %}{% trans "but you can visit his/her Speedy Net profile. " context user.get_gender %}{% trans "View " context request.user.get_gender %}{% trans "user's profile on Speedy Net." context user.get_gender %}
                            </a>
                        </div>
                    </div>
                {% endif %}
            {% endif %}
            {% block user_content_info %}
            {% endblock %}
        </div>
    </div>

{% endblock %}

我检查发现问题出在一个标签上,比如{% profile_picture user '256x200' html_class="rounded-lg" %},它调用以下标签:

@register.inclusion_tag('accounts/profile_picture.html')
def profile_picture(user, geometry, with_link=True, html_class=''):
    return {
        'user': user,
        'geometry': geometry,
        'width': geometry.split('x')[0],
        'with_link': with_link,
        'html_class': html_class,
    }

未打印的前缀仅在模板'accounts/profile_picture.html'中。你知道吗


Tags: corediv模板baseadminrequesthtmlcontext
3条回答

正如我在评论中提到的,发生这种情况是因为使用inclusion_tag呈现模板。你知道吗

问题是它们没有任何上下文变量,因此不会调用您的自定义context_processor。你知道吗

您应该在模板标记中使用takes_context=True,以使其接受上下文数据。你知道吗

现在起作用的代码是:

@register.inclusion_tag(filename='accounts/profile_picture.html', takes_context=True)
def profile_picture(context, user, geometry, with_link=True, html_class=''):
    context = copy.copy(context)
    context.update({
        'user': user,
        'geometry': geometry,
        'width': geometry.split('x')[0],
        'with_link': with_link,
        'html_class': html_class,
    })
    return context

如果要使用在包含模板中创建的上下文处理器var,请在包含之前添加:

{% add_admin_user_prefix as add_admin_user_prefix %}
{% include "whatever.html" %}

我不知道为什么一定要这么做,但对于我正在使用的包(django-postman)来说,这很管用。希望您的上下文var可以全局访问。你知道吗

你把上下文处理器加进去了吗设置.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',
            'Your context processor' 
            ]
       }
   }
]  

相关问题 更多 >

    热门问题