【问题标题】:How Django find correct Template variable from TemplateViewDjango 如何从 TemplateView 中找到正确的模板变量
【发布时间】:2019-08-30 01:45:12
【问题描述】:

我有这段代码:

# 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 中,我没有指定模型(在本例中为 CustomUser)。当我们想要访问和呈现数据库数据时,我们需要在视图中指定 Model 类(或者在本例中是 Form)。并从这里 Django 访问模板变量。不是吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    在您的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(存储用户的权限)添加到模板上下文中。

    【讨论】:

      【解决方案2】:

      通过 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',
                      ...
                  ],
              },
          },
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-27
        • 1970-01-01
        • 1970-01-01
        • 2012-09-12
        • 2021-07-17
        • 2012-08-14
        • 2018-06-01
        • 2013-11-27
        相关资源
        最近更新 更多