use*_*527 5 django django-views
我有一个自定义登录URL /视图/模板.我将@login_required装饰器用于需要登录的页面(我们称之为my_page).试图访问
my_site.com/my_page
Run Code Online (Sandbox Code Playgroud)
正确的电话
my_site.com/login/?next=/my_page/
Run Code Online (Sandbox Code Playgroud)
但我的视图无法解析?next =/my_page/my的值,而是总是重定向到我的默认值,即/ qa /在我的视图中:
def login_with_email(request):
error = ''
if request.method == 'POST':
if not request.POST.get('email', ''):
error = 'Please enter your email and password'
if not request.POST.get('password', ''):
error = 'Please enter your email and password'
if not error:
email = request.POST['email']
password = request.POST['password']
try:
user = User.objects.get(email=email)
user = authenticate(username=user.username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# ***
next_page = request.GET.get('next', '/qa/')
response = HttpResponseRedirect(next_page)
# ***
response.set_cookie('login_email', email, max_age=14*24*60*60)
return response
except User.DoesNotExist:
error = 'Invalid email and password combination'
Run Code Online (Sandbox Code Playgroud)
Urls.py:
url(r'^login/$', views.login_with_email),
Run Code Online (Sandbox Code Playgroud)
根据我下面的评论,我意识到我必须在 POST 处理之前从 url 中获取 next 的值(感谢@Anentropic 在灯泡上闪烁)。所以现在我获取 next 的值,将其传递到我的模板,我将其存储在隐藏字段中,最后在需要重定向时使用 request.POST.get 访问它:
修改后的视图:
def login_with_email(request):
error = ''
next = request.GET.get('next', '/qa/profile/private/')
if request.method == 'POST':
...
if user.is_active:
login(request, user)
next = request.POST.get('next', '/qa/profile/private/')
...
return render(request, 'qa/login_with_email.html', {'error': error, 'login_email': login_email, 'next': next,})
Run Code Online (Sandbox Code Playgroud)
在我的模板中:
<form method="post" action="." autocomplete="on">{% csrf_token %}
<p><input type="hidden" name="next" value="{{ next }}"/></p>
...
Run Code Online (Sandbox Code Playgroud)
注:此答案最初由问题提出者发布。我刚刚把它搬到这里了。
| 归档时间: |
|
| 查看次数: |
722 次 |
| 最近记录: |