Django如何从TemplateView查找正确的Template变量

时间:2019-04-08 20:36:00

标签: python django

我有这段代码:

# newspaper_project/urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
    path('admin/', admin.site.urls),
    path('users/', include('users.urls'))
    path('users/', include('django.contrib.auth.urls')),
]
# users/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('signup/', views.SignUp.as_view(), name='signup'),
]
# users/views.py
from django.urls import reverse_lazy
from django.views import generic
from .forms import CustomUserCreationForm

    class SignUp(generic.CreateView):
        form_class = CustomUserCreationForm
        success_url = reverse_lazy('login')
        template_name = 'signup.html'
<!-- templates/home.html -->
{% block title %}Home{% endblock %}
{% block content %}
    {% if user.is_authenticated %}
        Hi {{ user.username }}!
        <p><a href="{% url 'logout' %}">logout</a></p>
    {% else %}
        <p>You are not logged in</p>
        <a href="{% url 'login' %}">login</a> |
        <a href="{% url 'signup' %}">signup</a>
    {% endif %}
{% endblock %}

我的问题是: Django如何知道home.html模板中使用了哪种模型? (Django如何知道“用户名”?)

在TemplateView中,我没有指定Model(在这种情况下为CustomUser)。当我们要访问和呈现数据库数据时,我们需要在视图中指定Model类(在本例中为Form)。 Django从这里访问模板变量。不是吗?

2 个答案:

答案 0 :(得分:2)

TEMPLATES设置中,您启用了auth context processor

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

这会将user(当前登录的用户或匿名用户(如果尚未登录))和perms(存储用户的权限)添加到模板上下文。

答案 1 :(得分:0)

通过执行path('', TemplateView.as_view(template_name='home.html'), name='home')来设置URL只是配置视图的最简单方法。

您实际上并不会做任何复杂的事情,但是例如可以使用extra_context指定一些上下文变量;

path(
    '',
    TemplateView.as_view(
        template_name='home.html',
        extra_context={
            'page_title': 'Home Page',
        }
    ),
    name='home'
)

要保持urls.py的整洁,您可能会为首页创建另一个视图并以这种方式添加上下文变量;

class HomePageView(TemplateView):

    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['page_title'] = 'Home Page'
        context['user'] = CustomUser.objects.first()  # Filter for user here
        return context
<!-- templates/home.html -->
{% block title %}{{ page_title }}{% endblock %}

{% block content %}
    {% if request.user.is_authenticated %}
        Hi {{ request.user.username }}!

        The user you were interested in is {{ user.username }}

        <p><a href="{% url 'logout' %}">logout</a></p>
    {% else %}
        <p>You are not logged in</p>
        <a href="{% url 'login' %}">login</a> |
        <a href="{% url 'signup' %}">signup</a>
    {% endif %}
{% endblock %}

只要您在设置中具有请求上下文处理器,就可以像这样从请求对象访问登录用户;

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ...
                'django.template.context_processors.request',
                ...
            ],
        },
    },
]