我在views.py中有一个ListView类,如果要通过身份验证的用户显示另一个模板,我想添加一个条件
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'),
]
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
答案 0 :(得分: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 request.user.is_authenticated:
return ['page/index.html']
else:
return ['page/home.html']
如文档所述,此功能:
返回模板名称列表,以在渲染模板时进行搜索。 将使用找到的第一个模板。
如果指定了
template_name
,则默认实现将返回一个包含template_name
的列表(如果已指定)。
话虽如此,如果您不打算在home.html
页面上呈现列表,最好执行 redirect 到另一页面,而不是仅仅呈现页面。否则,如果您以后想在home.html
页面上添加更多内容,则每次都需要更新所有呈现此内容的视图。
basic implementation [GitHub]中的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]