Redirect to next URL in django FormView

[亡魂溺海] 提交于 2019-12-07 03:06:30

问题


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

Below is my code

The next parameter in the 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 above setup, how do I redirect to the next URL if it is defined, apart from the home page?


回答1:


Include the 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 will work for you.



来源:https://stackoverflow.com/questions/26988583/redirect-to-next-url-in-django-formview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!