0

a I have been watching a video which uses the following code to show errors.

{% if form.errors %}
<div class="alert alert-danger">
    {{form.errors.title.as_text}}
</div>
{% endif %}

But when I use it no errors show

If I use:

{% if form.errors %}
<div class="alert alert-danger">
    {% for error in form.errors %}
        <p>{{ error }}</p>
    {% endfor %}
</div>
{% endif %}

I get a single word eg. 'email' but the whole error text does not display.

It works fine on the video,

Could anyone tell me what i am doing wrong?

  • What does it give you without the `.as_text`? Maybe something you could iterate over? :) Have a look at https://docs.djangoproject.com/en/4.1/ref/forms/api/#django.forms.Form.errors – nigel239 Sep 03 '22 at 16:30
  • Nothing at all! – Cromwell1963 Sep 03 '22 at 16:33
  • Is there an error that should be displayed at that time for that field? – nigel239 Sep 03 '22 at 16:33
  • yes, an email format error – Cromwell1963 Sep 03 '22 at 16:46
  • using {{ form.errors.as_data}} returns {'email': [ValidationError(['Enter a valid email address.'])]} which is better, but not sure how to parse the bit I want from the dictionary. – Cromwell1963 Sep 03 '22 at 16:49
  • 1
    Cromwell you should be able to access it like any other dictionary in the template. Lets loop over the inner list that belongs to the key. `{% for error in form.errors.title %}{{error}}{%endfor%}` Otherwise, this may help you: https://stackoverflow.com/a/2462625/18020941 – nigel239 Sep 03 '22 at 16:57
  • 1
    I did try that at one point but was getting just the key, but have finally got a working version, thanks for your help. – Cromwell1963 Sep 05 '22 at 16:26

1 Answers1

1

Ok, imaged to get it to work using:

{% if form.errors %}
<div class="alert alert-danger">
    {% for key, value in form.errors.items %}
        {{ value.as_text }}
    {% endfor %}
</div>
{% endif %}

Thanks for your help