简体   繁体   中英

How to display the field "label" in django's builtin password validation errors?

I am using Django's builtin authentication class views and need to customize the error message displayed when password validation fails.

For example, in the builtin PasswordResetView , if I try to change my password to test , the following errors will display in my template:

  • new_password2

    • This password is too short. It must contain at least 8 characters.
    • This password is too common.

I would like to change new_password2 to New Password .

Here is the relevant part of my template for the PasswordResetView :

{% extends 'registration/base.html' %}

{% block card_body %}
  <div class="form-group">
    <label for="old_password">
      Old Password:
      {{ form.old_password }}
    </label>
  </div>
  <div class="form-group">
    <label for="new_password1">
      New Password:
      {{ form.new_password1 }}
    </label>
  </div>
  <div class="form-group">
    <label for="new_password2">
      Confirm Password:
      {{ form.new_password2 }}
    </label>
  </div>
  <div class="form-group">
    <input type="submit" value="Change" class="btn float-right login_btn">
  </div>
{% endblock card_body %}
{% block card_footer %}
  {% if form.errors %}
    <p class="d-flex justify-content-center links">
      {{ form.errors }}
    </p>
  {% endif %}
{% endblock card_footer %}
  1. Supply some dict to the template that will map form field names to labels you want like:

     fields_mapping = { 'old_password': 'Old password', 'new_password1': 'New password', 'new_password2': 'Confirm password' }
  2. Just manually iterate over errors and use the the mapping dic to convert field names to labels you want:

     {% for field_name in form.errors: %} {{ fields_mapping[field_name] }}: {% for err_message in form.errors[field_name]: %} * {{ err_message }} {% endfor %} {% endfor %}

Customize HTML/CSS there as you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM