Issue
I am unsure how to deal with different return options in Django.
Let me describe a fictive scenario:
I have an endpoint /books/5/ that returns an html showing infos about the book and the chapters it contains. Those are reachable at /books/5/chapters/ and /books/5/chapters/3/ for example.
I can make a POST to /book/5/chapters/ via a form with title etc. to create a new chapter. This can either succeed and a new chapter is created or it can fail, because of whatever reason.
To make my frontend a bit convenient I included the form to create chapters at the endpoint /book/5/. So I can see the books details and chapters and enter details for new chapter in this view in the form and click create.
My desired experience would be that I get a refresh of the /book/5/ to see the new state. If the post failed I would like to see a notification with the error message.
Is there a standard way how to do this? I have played around with JsonResponse and returning the next URL to go to and calling the endpoint with a JavaScript function that sets the current window to it. Vut I don't know how to display the error as notification and whether there is a better and common strategy for that problem anyway.
Solution
For 'refreshing' the detail book, you need to return a redirect to that book's detail page. For the notification with errors, I guess it depends on what the type of error it is: if it is a validation error, you can simply make use of the forms error messages. If they are errors you are defining outside the form, then you can either use Django's included messages
framework to send the message to the template or simply return a template variable.
- Redirecting Say your view looks like:
def add_book(request):
if request.method == "POST":
if book.is_valid():
book = form.savd()
return redirect(book.get_absolute_url())
This assumes you defined a get_absolute_url()
method on the book model (which you should if haven't).
- Error displaying Using the form's errors:
def add_book(request):
if request.method == "POST":
form = BookForm(request.POST)
if book.is_valid():
return redirect(....
return render(request, "add-book-template.html", dict(form=form)
This will return the same form and since it was bound with POST data, it will also contain any errors that might have happened. You can then access the errors in the template as:
{% if form.non_field_errors %}
<ul>
{% for error in form.non_field_errors %}
<li> {{error}} </li>
</ul>
{% endfor %}
{% endif %}
<form method="post">
{{form}}
</form>
This will display non_field_errors not associated with a particular field. If you need to display field errors, have a look here
Answered By - McPherson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.