How To Handle Errors In Django
Solution 1:
Django provided us a message framework which allow you to attach messages and then you can render it on your template by using JavaScript
or simply just use django template.
My favorite library to show message on my web application is toastr. You can go to the document page to see how you will integrate into your project.
On your views:
from django.contrib import messages
# ...defupload(request):
if"GET" == request.method:
messages.error(request, "There's no file uploaded")
return render(request, 'uploadpage/upload.html', {})
# ...
Then on your template you can use it like so:
...
<head>
...
<linkhref="toastr.min.css" /></head><body>
...
<scriptsrc="toastr.min.js"></script>
{% if messages %}
<script>
toastr.options = {
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000"
}
{% for message in messages %}
toastr.{{ message.tags }}("{{ message }}");
{% endfor %}
</script>
{% endif %}
</body>
message.tags
: Using to match with the function of toastr, for example if you want to show an error by usingmessages.error(...)
then themessage.tags
will beerror
, when your template rendered it turned totoastr.error("Your message here")
and then you'll see the toast message on your browser.
Hope that helps!
Solution 2:
There's two ways to go about it:
You can create a client-side check that prevents the form from being sent with Javascript. That is not Django-specific and you'll have no trouble finding examples.
You catch the fact that no file was sent and set an extra flag for the
upload.html
template. Untested example code:
message = None
data = Noneif request.FILES:
data = # process file
message = "Upload successful!"else:
message = "Please upload a file!"return render(request, 'upload.html', {"data": data, "message": message})
Then you can show the message
in the template:
{% if message %}
<divclass="message">{{message}}</div>
{% endif %}
Post a Comment for "How To Handle Errors In Django"