[Django]-How to handle errors correctly in django?

2πŸ‘

βœ…

The methodology here involves a couple things. First, within those views, you want to make sure you are getting those errors within an except block as your code does. Then you should return an HttpResponseRedirect object redirecting the user to the error page or another page where you would like for the user to return.

The next thing you can do is return a particular view for all errors of a type on the site when they hit urls.py. For example, to redirect all 404 errors, add the following code to the base site urls.py

handler404 = 'App.views.error_404_view'

Then, in the view simply return the custom error page you’d like or perform a new HttpResponseRedirect

def error_404_view(request, exception):
    return render(request, 'error_404.html')
πŸ‘€Gracen Ownby

2πŸ‘

First of all you should think on what errors you want to expose. Usually 4xx errors (Errors that are attributed to the client-side) are disclosed so the user may correct the request. On the other side, 5xx errors (Errors that are attributed to the server-side) are usually only presented without information.

try something like that –

    try:
        test_method(form.cleaned_data)
    except `PermissionError` as e:
        status_code= 403
πŸ‘€user16514821

Leave a comment