重定向到django FormView中的下一个URL

编程入门 行业动态 更新时间:2024-10-05 01:20:07
本文介绍了重定向到django FormView中的下一个URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 Django 1.7 与 Python 3.4 。我有一个场景,我希望用户在登录后被重定向到另一个视图,如 next GET参数中定义的。但是,根据我目前的设置,他们总是被重定向到主页。我希望有一种方法可以在 FormView 类的 get_success_url 中执行此操作。

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.

以下是我的代码

URL中的下一个参数

The next parameter in the URL

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

通过上述设置,除了主页之外,如何定义它,如何重定向到下一个URL?

With the above setup, how do I redirect to the next URL if it is defined, apart from the home page?

推荐答案

将数据作为GET参数包含在您的成功URL中。

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

希望这将为您工作。

更多推荐

重定向到django FormView中的下一个URL

本文发布于:2023-11-02 06:33:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重定向   django   URL   FormView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!