简体   繁体   中英

Django get form errors after redirect

I have a page that shows the details of a person. On the same page it also shows the many friends that the person has. I have a button that lets me add a friend to the person, when I click on it, a bootstrap modal shows.

/person/10 (this is the person's page)
/person/10/add-friend (this is the POST endpoint to add a friend)

If the form data is valid, the new friend is added to the person and is redirected back to the person details page. The problem is, if the data is invalid, I can't seem to get the form errors after the redirect.

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)

Many say that I should render the persons detail page and send the form as context if the form validation fails, but the problem is, the URL will be /person/10/add-friend instead of /person/10

Am coming from PHP/Laravel, doing something like what I want above is just too simple/basic, but can't get my head around how it's supposed to be done in Django.

If you really want to stick with this approach and redirect to person_detail and let the user correct the errors there I think you have two options to pass the errors to person_detail :

A) Use sessions

B) Use the messages framework

For A) you can simply add the form errors like this:

request.session['form_errors'] = form.errors.as_json()

For B) you would add a message like this:

from django.contrib import messages
messages.add_message(request, messages.INFO, 'There has been an error...')

And then display it like this in your template on the redirected page:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM