Django: Force User is anonymous to logout page bassed in generic.DetailView. Hello, this is my last problem in my project. We use generic.DetailView
in my dashboard for member. So the problem is, how to redirect anonymous user in django generic?
We have an error like this: Page not found (404)
How to handle it? and why would an error 404?
In docs of Django generic, have a function of dispatch(request, *args, kwargs)**, the method that accepts a request
argument plus arguments, and returns a HTTP response.
So, we handle it with dispatch
function in django generic views. There is similiar with what was asked in stackoverflow and hasbeen answered with someone there.
And this is my script in my last project:
class Dashboard_Member(generic.DetailView):
template_name = "dashboard_member.html"
def dispatch(self, request, *args, **kwargs):
if request.user.is_anonymous():
return HttpResponseRedirect('/accounts/login/')
else:
return super(Dashboard_Member, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context_data = super(Dashboard_Member, self).get_context_data(**kwargs)
....
return context_data
So, anonymous user will automatically redirect to login page, or whatever you need to redirect it. This dispatch
function also available for generic.ListView
Helpfully can help…