Search code examples
djangotemplatesdjango-formsdjango-authentication

How to display the errors of the "Django authentication system" in a template?


I use Django authentication system for my project. According to the structure of the template, I have to use the form fields individually. This is signup template:

<section class="form-container___auth">


<div class="form-container">
  <img src="{% static './images/white-logo-all.png'%}" />

    <p class="title">ثبت نام دانش آموز</p>


    <form class="form" method="post" action="">
        {% csrf_token %}
        <div class="input-group">
            <label for="email">ایمیل</label>
            <input type="email" name="{{ form.email.name }}" id="{{ form.email.id_for_label }}" placeholder="" value="{{ form.email.key }}">
        </div>

    <div class="input-group">
            <label for="email">نام کاربری</label>
            <input type="text" name="{{ form.username.name }}" id="{{ form.username.id_for_label }}" placeholder="" value="{{ form.username.key }}">
        </div>

        <div class="input-group">
            <label for="password">رمز عبور</label>
            <input type="password" name="{{ form.password1.name }}" id="{{ form.password1.id_for_label }}" placeholder="" value="{{ form.password1.key}}">
            
        </div>

        <div class="input-group">
            <label for="password">تکرار رمز عبور</label>
            <input type="password" name="{{ form.password2.name }}" id="{{ form.password2.id_for_label }}" placeholder="" value="{{ form.password2.key}}">
        </div>

        <button type="submit" class="sign">ثبت نام</button>
    </form>
    <div class="social-message">
        <div class="line"></div>
        <p class="message">ورود</p>
        <div class="line"></div>
    </div>
    
    <p class="signup">.اگر حساب کاربری دارید ، وارد سایت شوید
        <a rel="noopener noreferrer" href="{% url 'login' %}" class="">ورود</a>
    </p>
</div>
</section>

Django authentication system detects the errors and provides them to you, but I don't know how to display the errors of each field in my template. Now how can display the errors?


Solution

  • The form is just like any other form, so you can render the form manually [Django-doc] where for each field, you can access the errors with:

    {{ form.fieldname.errors }}

    and for fields not specific to a field, we can use:

    {{ form.non_field_errors }}

    You can also take control about rendering the errors by enumerating over the errors with:

    {% for error in form.fieldname.errors %}
        <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}