[英]Redirecting to originally requested page after login in Django
I am new to Django. 我是Django的新手。 I needed to code the login feature to redirect to originally requested URL after login.
登录后,我需要对登录功能进行编码以重定向到最初请求的URL。 I looked around and found the following on a stackoverflow thread.
我环顾四周,在stackoverflow线程上发现了以下内容。
django redirect after login not working "next" not posting? django重定向登录后无法正常工作“下一步”不张贴?
I see the following in the Django documention 我在Django文档中看到以下内容
login_required() does the following:
login_required()执行以下操作:
If the user isn't logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string.
如果用户未登录,请重定向到settings.LOGIN_URL,并在查询字符串中传递当前的绝对路径。 Example: /accounts/login/?next=/polls/3/.
例如:/ accounts / login /?next = / polls / 3 /。
I also read that the login() method of django.contrib.auth package passes next
to the template. 我还阅读了django.contrib.auth软件包的login()方法在模板
next
传递。 So I defined the login() function in my view (I cannot use the one from the 'auth' package since I need some customization). 因此,我在视图中定义了login()函数(由于需要自定义,因此无法使用'auth'包中的那个)。
def login(request):
next = request.GET['next']
return render(request, 'user/login.html', {'next': next})
In my template 在我的模板中
<form method="post" action="{% url 'user:login_user' %}" >
{% csrf_token %}
<p><label for="id_username">Username:</label> <input autofocus="" id="id_username" maxlength="254" name="username" type="text" required /></p>
<p><label for="id_password">Password:</label> <input id="id_password" name="password" type="password" required /></p>
<input type="hidden" name="next" value="{{next}}" />
<button type="submit">Login</button>
</form>
In my login_user() function, if I see that the value of next is present, I redirect to that URL once I have logged the user in. This works for me fine. 在我的login_user()函数中,如果看到存在next的值,则在用户登录后便重定向到该URL。这对我来说很好。
However, solution presented in the thread above was a bit more involved. 但是,上面线程中提出的解决方案涉及更多。 I am curious as to why is it necessary to do all that.
我很好奇为什么有必要做所有这些事情。 What am missing here?
这里缺少什么?
Thanks 谢谢
try changing your 尝试改变你的
<button type="submit">Login</button>
to 至
<input type="submit" value="Login" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.