我遇到了问题,但找不到解决方案。
登录后,我试图重定向到上一页。在提交后尝试请求request.POST.get()时,?next = request.path以某种方式不返回任何内容。
这是我的HTML代码,它将用户引导到登录页面,将request.path用作“登录后的下一页”值。
{% if user.is_authenticated %}
<button class="btn" data-toggle="modal" data-target="#inquiryModal">
<a class="btn btn-primary border rounded-0"
role="button" href="#">Make an Inquiry</a>
</button>
{% else %}
<a class="btn btn-primary border rounded-0" role="button"
href="{% url 'login' %}?next={{ request.path|urlencode }}"
>Make An Inquiry</a>
{% endif %}
这是登录页面的html代码。
<div class="login-clean" style="background-color: #fff;">
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<!--- ALERTS -->
{% include 'partials/_alerts.html' %}
<div class="form-group">
<input class="form-control" type="email" name="email" placeholder="Email"></div>
<div class="form-group">
<input class="form-control" type="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<button class="btn btn-primary btn-block" type="submit">Log In</button>
</div>
</form>
</div>
Views.py文件
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
valuenext = request.POST.get('next')
print(valuenext)
user = auth.authenticate(username=email, password=password)
# if user is found and not from listing page login and redirect to dashboard
if user is not None and valuenext == "":
auth.login(request, user)
messages.success(request, 'You are now succesfully logged in')
return redirect('dash_inquiries')
# if user is found and from specific listing page login and redirect to the listing
elif user is not None and valuenext != "":
auth.login(request, user)
print("success")
messages.success(request, 'You are now logged in')
return redirect(valuenext)
else:
messages.error(request, 'Invalid credentials')
return redirect('login')
else:
return render(request, 'accounts/login.html')
我在这里做错了什么?指向登录页面时,下一个值在url中传递,但由于后端一直返回None,所以我似乎无法正确地在后端获取()下一个值。
先谢谢了。
答案 0 :(得分:0)
点击以下按钮将发送一个GET
请求。
<a class="btn btn-primary border rounded-0" role="button"
href="{% url 'login' %}?next={{ request.path|urlencode }}">Make An Inquiry</a>
此获取请求将呈现accounts/login.html
模板。
您仅针对request.POST.get('next')
个请求解析POST
。
<form action="{% url 'login' %}" method="POST">
您需要使用form
标签,使其看起来像
<form action="{% url 'login' %}next={{ next }}" method="POST">
要解决上述问题,您需要为request.GET
解析“ next”,并将其添加到context
中以进行响应。
if request.method == 'POST':
# handle POST
else:
next = request.GET.get('next', '')
context = {'next': next}
return render(request, 'accounts/login.html', context=context)
然后,将此next
添加到form.action
中。
<form action="{% url 'login' %}next={{ next }}" method="POST">
答案 1 :(得分:0)
好的,所以我不确定我是否将下一个值传递到登录表单中,因此解决方案是添加一个隐藏输入以获取请求中的下一个值:
<input type="hidden" name="next" value="{{ request.GET.next }}" />