Class based view for another view

Is it possible to have a class view delegate on a specific class based view? In particular, what I would like to do is to have / point to a view called "home" and a home view with a delegate to view A if the user is logged in, or view B if the user is not logged in. Alternatively, I could do a redirect to a different url. I'm not sure what would be best here.

+4
source share
3 answers

You can call another view from the view just like in the urls

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" 
+7
source

You can simply redirect to a different url, and that url is also supported by the class based view.

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 
+1
source

The best practice for user authentication is to use 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 
0
source

All Articles