【问题标题】:how do I add template conditions in the ListView class?如何在 ListView 类中添加模板条件?
【发布时间】:2019-10-12 10:42:26
【问题描述】:

我在views.py中有一个ListView类,如果经过身份验证的用户显示另一个模板,我想添加一个条件

urls.py

from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import (
    PostListView,
)

urlpatterns = [
    path('', PostListView.as_view(), name='index'),
]

Views.py

from django.shortcuts import render, get_object_or_404
from django.views.generic import (
    ListView,
)
from .models import Post
from django.contrib.auth.models import User
from django.contrib.auth import authenticate


class PostListView(ListView):
    model = Post
    template_name = 'page/index.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 7

我要补充

        if self.request.user.is_authenticated:
            template_name = 'page/index.html'
        else:
            template_name = 'page/home.html'

Django 2.2.x

【问题讨论】:

    标签: django django-models django-views django-urls


    【解决方案1】:

    您可以覆盖get_template_names function [Django-doc]:

    class PostListView(ListView):
        model = Post
        context_object_name = 'posts'
        ordering = ['-date_posted']
        paginate_by = 7
    
        def get_template_names(self):
            if self.request.user.is_authenticated:
                return ['page/index.html']
            else:
                return ['page/home.html']

    正如文档所说,这个函数:

    返回一个模板名称列表,以便在呈现模板时进行搜索。 将使用找到的第一个模板

    如果指定了template_name,默认实现将返回一个包含template_name(如果指定)的列表。

    话虽如此,如果您不打算在您的home.html 页面上呈现列表,那么执行重定向 到另一个页面可能会更好,而不是仅仅呈现一个页面。否则,如果您以后想向home.html 页面添加更多内容,则每次都需要更新所有呈现此内容的视图。

    TemplateResponseMixin [Django-doc] 中的basic implementation [GitHub] 是这样的:

    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if render_to_response() is overridden.
        """
        if self.template_name is None:
            raise ImproperlyConfigured(
                "TemplateResponseMixin requires either a definition of "
                "'template_name' or an implementation of 'get_template_names()'")
        else:
            return [self.template_name]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2020-11-03
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多