1๐
I would override get_template_names
to set the template name, and get_context_data
to set the context data. You can access the user with self.request.user
, and check whether they are logged in with the is_authenticated()
method.
class HomepageView(TemplateView):
def get_context_data(self, **kwargs):
"""
Returns a different context depending
on whether the user is logged in or not
"""
context = super(HomepageView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated():
context['user_type'] = 'logged in'
else:
context['user_type'] = 'guest'
return context
def get_template_names(self):
"""
Returns a different template depending
on whether the user is logged in or not
"""
if self.request.user.is_authenticated():
return 'logged_in_homepage.html'
else:
return 'guest_homepage.html'
Note that I have overridden different methods of TemplateView
to customize the functionality, rather than calling one method for guest or another method for logged in users that does everything. If you really want to call one method that does everything, then it might be better to use a function view instead.
1๐
You know, your question is really open-ended. There are loads of different ways to do it.
I would probably subclass TemplateView
, overwriting the dispatch
method to set a different template based on the scenario.
To figure out how your logic fits in with the various CBVs, I recommend the Classy Class-Based-Views resource, so you can see which methods are called where.
- [Answered ]-Python django run bash script in server
- [Answered ]-How to open a Popup window which contains a graph written in javascript?
- [Answered ]-Doing some processing locally before uploading