Python Django在重定向后获取表单错误

Python Django在重定向后获取表单错误,python,django,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_fri

我有一个页面显示一个人的详细信息。在同一页上,它还显示了此人的许多朋友。我有一个按钮,让我添加一个朋友的人,当我点击它,一个引导模式显示

/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)
许多人说,如果表单验证失败,我应该呈现persons detail页面并将表单作为上下文发送,但问题是,URL将是
/person/10/add friend
,而不是
/person/10


我来自PHP/Laravel,做上面我想做的事情太简单/基本了,但是我无法理解在Django应该如何做。

如果你真的想坚持这种方法,并重定向到
person\u detail
,让用户在那里纠正错误,我想你有两种选择可以将错误传递到
person\u detail

A)使用

B)使用

对于A)您可以简单地添加如下表单错误:

request.session['form_errors'] = form.errors.as_json()
from django.contrib import messages
messages.add_message(request, messages.INFO, 'There has been an error...')
对于B)您可以添加如下消息:

request.session['form_errors'] = form.errors.as_json()
from django.contrib import messages
messages.add_message(request, messages.INFO, 'There has been an error...')
然后在重定向页面的模板中按如下方式显示:

{% for message in messages %}
     {{ message }}
{% endfor %}