我正在使用 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/newviews.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
发布评论