MarcJuegos_Yt
MarcJuegos_Yt

Reputation: 127

Raising Errors in Django

I am working on a website that translates dna chains into proteins. Here's the thing, a dna chain must be divisible by 3. So if the user inputs a value which is not divisible by three, it raises an arithmetic error. Here's the code:

  if len(phrase) % 3:
                raise ArithmeticError("DNA chain must be divisible by 3")
        return protein

The code works because it raises the error page. enter image description here

However, I would want the error to be raised in the template where I input the chain. Basically, what I want is the error to appear below the translated button. Like a string or something that says "DNA CHAIN MUST BE DIVISIBLE BY 3" enter image description here

How can I do that.

Here's the html code for the template in case you need to make changes.

Upvotes: 1

Views: 48

Answers (1)

Saijal Shakya
Saijal Shakya

Reputation: 152

You can simply use Django Message Framework.

In views

if len(phrase) % 3:
    messages.error(request, "DNA chain must be divisible by 3")
    return HttpResponseRedirect('name_of_url')
return protein

In Django Template

{% if messages %}
    {% for msg in messages %}
        msg
    {% endfor %}
{% endif %}

For more information, go through the documentation: https://docs.djangoproject.com/en/3.1/ref/contrib/messages/

Upvotes: 1

Related Questions