“下一个”参数,重定向,django.contrib.auth.login [英] The "next" parameter, redirect, django.contrib.auth.login

查看:216
本文介绍了“下一个”参数,重定向,django.contrib.auth.login的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户重定向到默认的/ account / profile /,当我知道我可以覆盖重定向网址时,将用户重定向到自定义网址/ gallery /(username)/在我的settings.py中,我的url是动态的,因此它将无法工作。

I'm trying to redirect users to custom url "/gallery/(username)/" after successfully logging in. It currently redirects to the default "/account/profile/" While I know what I can override the redirect url in my settings.py, my url is dynamic thus it will not work.

文档规定我需要使用下一个参数和上下文处理器。我的模板中有{{next}},但我对如何实际传递/ gallery /(username)感到困惑。任何帮助将不胜感激。

Documentation states that I need to use the "next" parameter and context processors. I have the {{next}} in my template, but I'm confused on how to actually pass the "/gallery/(username)". Any help would be greatly appreciated.

ps我试图避开写我自己的登录视图。

p.s I'm trying to steer away from writing my own login view.

推荐答案

我承认我通常会使用2个重定向来获得这样的工作。

I confess I usually use 2 redirects in order to get something like this to work.

首先, code> registration / login.html 页面。您可以在认证文档,使过程更容易一些。但是,不要使用上下文中的动态'{{next}} 变量,而是将其下一个值更改为登录用户的通用登录视图。 p>

First, Make your own registration/login.html page. You can copy-and-paste the html example in this section of the authentication docs to make the process a little easier. Instead of using the dynamic '{{ next }} variable from the context, however, hardwire the value of next to go to a generic landing view of logged-in users

<input type="submit" value="login" />
<input type="hidden" name="next" value="/gallery/" />

然后,在映射到 / gallery / URL,从请求中提取User对象(因为用户现在将被登录,特别是如果图库视图包裹在 @permission_required @login_required 装饰器使用该视图重定向到相应的用户特定的图库页面:

Then, in the view that you map to the /gallery/ URL, extract the User object from the request (since the user will now be logged in, especially if the gallery view is wrapped in a @permission_required or @login_required decorator. Use that view to redirect to the appropriate user-specific gallery page:

@login_required
def gallery(request):
    url = '/gallery/%s/' % request.user.username
    return HttpResponseRedirect(url)

这篇关于“下一个”参数,重定向,django.contrib.auth.login的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆