Redirecting to the following url in django FormView

I am using Django 1.7 with Python 3.4 . I have a scenario where I want users to be redirected to another view, as defined in the next GET parameter, after logging in. But with my current setup, they are always redirected to the home page. I was hoping there was a way to do this in the get_success_url class.

Below is my code

Next parameter in url

 http://localhost:8000/login/?next=/ads/new 

views.py

 from django.views.generic.edit import FormView class LoginView(FormView): template_name = 'users/login.html' form_class = LoginForm def get_success_url(self): return reverse('home') def form_valid(self, form): form.user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, form.user) messages.info(self.request, 'Login successful') return super(LoginView, self).form_valid(form) 

urls.py

 url(r'^login/', LoginView.as_view(), name='login'), url(r'^new$', 'apps.adverts.views.add_new_advert', name='new_advert'), # URL to use after login, in next param 

With the setting above, how do I redirect to the next URL if it is defined other than the main page?

+5
source share
1 answer

Include data as GET parameters in your success URL.

 def get_success_url(self): # find your next url here next_url = self.request.POST.get('next',None) # here method should be GET or POST. if next_url: return "%s" % (next_url) # you can include some query strings as well else : return reverse('home') # what url you wish to return 

Hope this works for you.

+7
source

Source: https://habr.com/ru/post/1207098/


All Articles