是否可以将基于类的视图委托给特定的基于类的视图?具体来说,我想做的是/指向一个名为'home'的视图,如果用户已登录,则指向View A的主视图;如果没有用户登录,则指向View B.或者我可以执行重定向到其他网址。我不确定这里最好的做法是什么。
答案 0 :(得分:8)
您可以使用与网址
相同的方式在视图中调用其他视图class HomeView( TemplateView ):
template_name="index.html"
def dispatch( self, request, *args, **kwargs ):
if request.user.is_authenticated():
view=UserHomeView.as_view()
return view( request, *args, **kwargs )
return super( HomeView, self ).dispatch( request, *args, **kwargs )
class UserHomeView( TemplateView ):
template_name="user.html"
答案 1 :(得分:1)
您只需重定向到其他网址,该网址也会通过基于类的视图提供。
urls.py
url(r'^$', HomeView.as_view(), name='home'),
url(r'^login/', LoginView.as_view(), name='login'),
url(r'^welcome/$', WelcomeView.as_view(), name='welcome')
views.py
class HomeView(TemplateView):
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('welcome'))
else:
return HttpResponseRedirect(reverse('login'))
class WelcomeView(TemplateView):
def get(self, request, *args, **kwargs):
#do something
class LoginView(TemplateView):
def get(self, request, *args, **kwargs):
#show login page
答案 2 :(得分:0)
确保用户必须通过身份验证的最佳做法是使用Mixin:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
class LoginRequiredMixin(object):
u"""Ensures that user must be authenticated in order to access view."""
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class MyView(LoginRequiredMixin, TemplateView):
def get(self, request, *args, **kwargs):
#do something