Skip to content Skip to sidebar Skip to footer

How To Handle Errors In Django

I want to make my django app as user friendly as possible and I want to handle appropriate errors and have it push out an error message sort of like an alert in javascript. I want

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 using messages.error(...) then the message.tags will be error, when your template rendered it turned to toastr.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:

  1. 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.

  2. 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"