Django如何在POST后执行条件重定向?
我有一个表单,其中显示了用户配置文件中的一些字段。在此表单中,配置文件中的字段被禁用。如果详细信息已过时,用户可以转到“编辑纵断面图”并更新详细信息。为此,我在表单的模板中包含了一个按钮。更新配置文件后,我希望用户返回表单。最后一部分是我遇到的问题 从表单编辑配置文件的链接如下所示:Django如何在POST后执行条件重定向?,django,redirect,Django,Redirect,我有一个表单,其中显示了用户配置文件中的一些字段。在此表单中,配置文件中的字段被禁用。如果详细信息已过时,用户可以转到“编辑纵断面图”并更新详细信息。为此,我在表单的模板中包含了一个按钮。更新配置文件后,我希望用户返回表单。最后一部分是我遇到的问题 从表单编辑配置文件的链接如下所示: <a class="btn btn-outline-info" href="{% url 'profile'%}?next={% url 'submission_resume' %}">Edit Pro
<a class="btn btn-outline-info" href="{% url 'profile'%}?next={% url 'submission_resume' %}">Edit Profile</a>
问题在于,在“编辑纵断面图”中,我不知道如何实现条件重定向:
def profile(request):
""" View and edit the profile. It requires user to be login """
if request.method == 'POST':
form = UserModifyForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been updated!')
#??? if next in url go back to the form ???
#??? return redirect(???) ???
#??? else: ???
return redirect('profile')
else:
form = UserModifyForm(instance=request.user)
#--> Dict for template with the forms
context = {
'form': form,
}
#--> Show profile page
return render(request, 'user_profile.html', context)
#---
使用以下命令:
redirect_to = request.POST.get("next", "profile")
return redirect(redirect_to)
我将视图更改为:
def profile(request):
""" View and edit the profile. It requires user to be login """
if request.method == 'POST':
form = UserModifyForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been updated!')
redirect_to = request.POST['redirect_to']
return redirect(redirect_to)
else:
redirect_to = request.GET.get("next", "profile")
form = UserModifyForm(instance=request.user)
#--> Dict for template with the forms
context = {
'redirect_to': redirect_to,
'form' : form,
}
#--> Show profile page
return render(request, 'user_profile.html', context)
#---
在模板中包括:
<input type="hidden" name='redirect_to' value="{{redirect_to}}">
在
标记内
但我仍然想知道是否有更简单的方法来做到这一点
request.POST.get('redirect_to', None))
如果存在,上面的语句将给重定向_to值,否则它将返回'None'
所以你可以试试
request.POST.get('redirect_to', 'replace the value with default view where you want to redirect'))
如果您只是想重定向到上一页,也可以尝试下面的代码
redirect(request.META.get('HTTP_REFERER'))
提交表单时用户数据是否发生了更改,唯一的问题是重定向?可能您正在向视图发送
GET
请求。是的,用户配置文件已更新。重定向是唯一的问题。请您稍微清楚地说明您的要求,是在表单编辑和保存时,您希望将用户重定向到“下一个”页面,还是在没有任何表单提交时,您希望将用户重定向到默认页面。是否正确?@Pradeep用户开始填写表单,并意识到表单中显示的联系人详细信息已经过时,因此他在表单中单击一个按钮,将用户带到个人资料编辑页面。用户完成对配置文件的编辑并点击submit保存配置文件中的更改。如果用户从表单到达“编辑配置文件”页面,则页面会在保存更改后将用户重定向回表单。如果不是来自表单,则使用新值显示配置文件。保存表单后,可以在views.py中使用“return redirect(request.META.get('HTTP\u REFERER')”)将用户重定向到其上一个配置文件page@Pradeep是的,但这不仅仅是回去。如果用户在主页上并且决定更新配置文件,那么在更新之后,我希望用户留在配置文件页面上。如果用户在表单中并决定更新配置文件,那么它将返回。问题是如何在post变量中包含重定向到。正如我的回答中的一条评论所解释的那样,返回选项也是不够的
redirect(request.META.get('HTTP_REFERER'))