Is it possible to have a class based view delegate to a particular class-based view? Specifically what I'd like to do is have / point to a view called 'home' and the home view with delegate to View A if the user is logged in, or View B if no user is logged in. Alternatively I could do a redirect to a different URL. I'm not sure what would be the best practice here.
You can call another view from within a view in the same manner used in 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"
You can just redirect to a different url and that url is also served by a 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With