如何在 ListView class 中添加模板条件?

how do I add template conditions in the ListView class?

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

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

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

class PostListView(ListView):
    model = Post
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 7

    def <b>get_template_names</b>(self):
        if self.request.user.is_authenticated:
            return ['page/index.html']
        else:
            return ['page/home.html']

如文档所述,此函数:

Returns a list of template names to search for when rendering the template. The first template that is found will be used.

If template_name is specified, the default implementation will return a list containing template_name (if it is specified).

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

因此basic implementation [GitHub] in the TemplateResponseMixin [Django-doc]是:

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]