首页 > 解决方案 > 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 中完成。

标签: pythondjango

解决方案


如果您真的想坚持使用这种方法并重定向到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 %}

推荐阅读