Ryan Currah
Ryan Currah

Reputation: 1105

How to raise errors in Django when running Python script?

Right now I am writing an Python script that will execute once a form is completed. Then I run my script and I want to display any errors to the web page when it runs. What is the method to accomplish, Django specific or Python specific?

r = requests.post("http://1.1.1.1:8080/unsecured/cloud/api/auth", data={}, auth=('user', 'password'))
if r.status_code == 200:
    data = r.json()
    if 'access' in data:
        cookie = {'simpletoken': data['access'].get('id')}
else:
    # raise some kind of error that will be displayed on the webpage

I assume raising the Django ValidationError exception would be approproate. But I am not sure. Any help would be great! Thanks.

Upvotes: 0

Views: 91

Answers (1)

Andrew Gorcester
Andrew Gorcester

Reputation: 19953

You can raise any exception you like, but all of them will result in a generic 500 error displayed to the user (the real exception will be displayed in your logs). If DEBUG is set to True then you will see a full traceback, but that is not what you should expect in production.

If this is not what you want, then you need to wrap the call to your exception-generating code from your view in a try/except block. Then in the "except", have code that displays a page with all the information about the error you need. Just be wary of security issues where your exception reveals sensitive information about your infrastructure.

As far as which error to raise exactly, I'm not sure ValidationError is the exact one you need, but as @dm03514 suggested you can create your own error, or you can look through other exception subclasses that already exist. Ultimately it doesn't matter that much which exception you use, as long as there's no risk of getting it confused with something else.

Upvotes: 1

Related Questions