I am trying to limit the access for a view using Django LoginRequiredMixin. If the user is not logged in it will redirect to the login page. But the problem is that after login it is not redirecting to the user typed url instead it goes to the default page?
For example user tries to login to the page site/site-create. If the user is not logged in it goes to the login page. After the login it goes to the default page of login.Here I want to redirect the user to site/site-create page.Example view
class CreateSite(LoginRequiredMixin, CreateView):
model = Site
fields = ['name','site_category','description',]
Login/views.py
class LoginViewClass(FormView):
"""
Provides the ability to login as a user with a username and password
"""
form_class = AuthenticationForm
template_name = 'login/login_view_class.html'
def get_context_data(self, **kwargs):
context = super(LoginViewClass, self).get_context_data(**kwargs)
create_all_menus(ALL_MENUS)
return context
def post(self, request):
username = self.request.POST['username']
password = self.request.POST['password']
user = authenticate(username=username, password=password)
Edit--> login views.py added How can I do that? Thank You
The LoginRequiredMixin will redirect to the login_url adding the originating URL as a parameter redirect_field_name (link to code).
login_url and redirect_field_name are two attributes you can define in your view like this:
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
This example would redirect to /login/?redirect_to={current_url}
This two fields have default values when there are not specified:
login_url defaults to settings.LOGIN_URL (link to code)redirect_field_name defaults to the value next (link to code)In your case it seems that your login view doesn't take the next URL parameter. The two options are:
next URL parameter.redirect_field_name = 'your_field_name'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