python - Django在重定向后得到表单错误
问题描述
我有一个页面显示一个人的详细信息。在同一页面上,它还显示了此人拥有的许多朋友。我有一个按钮,可让我向此人添加朋友,当我单击它时,会显示引导模式。
/person/10 (this is the person's page)
/person/10/add-friend (this is the POST endpoint to add a friend)
如果表单数据有效,则将新朋友添加到人员并重定向回人员详细信息页面。问题是,如果数据无效,重定向后我似乎无法收到表单错误。
def add_friend(request, id=None):
person = get_object_or_404(Person, pk=id)
form = FriendForm(request.POST)
if form.is_valid():
# code to save the friend to the person
#here I want to send the form errors if the form failed, but don't think we can send context with redirect
return redirect('person_detail', id=person.pk)
许多人说如果表单验证失败,我应该呈现人员详细信息页面并将表单作为上下文发送,但问题是,URL 将/person/10/add-friend
不是/person/10
我来自 PHP/Laravel,做我想要的上面的事情太简单/基本,但我无法理解它应该如何在 Django 中完成。
解决方案
如果您真的想坚持使用这种方法并重定向到person_detail
并让用户更正那里的错误,我认为您有两个选项可以将错误传递给person_detail
:
A)使用会话
B)使用消息框架
对于A),您可以简单地添加如下表单错误:
request.session['form_errors'] = form.errors.as_json()
对于B),您将添加如下消息:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'There has been an error...')
然后在重定向页面上的模板中像这样显示它:
{% for message in messages %}
{{ message }}
{% endfor %}
推荐阅读
- vba - 当我使用按钮运行宏时,由于内存不足,excel 无法完成
- python - 如何从pyspark调用存储过程
- oracle-apex - 单击按钮时如何在 apex builder 中关闭窗口
- typescript - 将 Typescript 编译为原生浏览器 ES 模块
- html - 接受输入类型验证问题
- json - Flutter - 读取JSON文件时错误没有这样的文件或目录
- java - 错误:二元运算符“&&”的操作数类型错误。这个错误是什么意思?
- snmp - 如果我没有 LA,我可以使用 SNMP 来发现设备吗
- java - java中的“this”不是指当前对象的成员。但是,这取决于访问点。为什么?
- python - Pyomo:KeyError:“索引'(0,1,1)'对于索引组件'x_ijl'无效”