使用FormView重定向到Django中的下一个URL

时间:2015-07-08 02:38:41

标签: python django

我的登录重定向到FormView时遇到问题。它始终会将我重定向到accounts/profile/,然后url/accounts/login/?next=/add/posts/将我带到网址add/post/

class LoginForm(FormView):
    form_class = AuthenticationForm
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'accounts/login.html'
    success_url = ''

    @method_decorator(csrf_protect)
    @method_decorator(never_cache)
    def dispatch(self, *args, **kwargs):
        return super(LoginForm, self).dispatch(*args, **kwargs)

    def form_valid(self, form):

        self.check_and_delete_test_cookie()
        login(self.request, form.get_user())
        return super(LoginForm, self).form_valid(form)

    def form_invalid(self, form):

        self.set_test_cookie()
        return super(LoginForm, self).form_invalid(form)

    def get_success_url(self):
        if self.success_url:
            redirect_to = self.success_url
        else:
            redirect_to = self.request.REQUEST.get(self.redirect_field_name, '')

        netloc = urlparse.urlparse(redirect_to)[1]
        if not redirect_to:
            redirect_to = settings.LOGIN_REDIRECT_URL
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)


        elif netloc and netloc != self.request.get_host():
            redirect_to = settings.LOGIN_REDIRECT_URL
            redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)
        return redirect_to

    def set_test_cookie(self):
        self.request.session.set_test_cookie()

    def check_and_delete_test_cookie(self):
        if self.request.session.test_cookie_worked():
            self.request.session.delete_test_cookie()
            return True
        return False

    def get(self, request, *args, **kwargs):

        self.set_test_cookie()
        return super(LoginForm, self).get(request, *args, **kwargs)

1 个答案:

答案 0 :(得分:1)

我习惯使用自定义类来处理这个小功能,例如:

from django.urls import reverse_lazy

class NextUrlMixin(object):
    """ Allows to redirect a view to its correct success url. """
    def get_success_url(self):
        if 'next' in self.request.GET:
            return self.request.GET.get('next')
        return reverse_lazy('index')

并在你的CBV中使用它:

class LoginForm(NextUrlMixin, FormView):
     # rest of your code

(注意:对于Django< 1.10,请使用from django.core.urlresolvers import reverse_lazy