Почему мое условие if не выполняется так, как ожидается в шаблоне Django?
что мне делать?
Итак, у меня есть форма регистрации, и я хочу проверить, если django message == "password not strong enough"
и если это условие истинно, то выполнить этот фрагмент HTML кода
<div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert">
<p style="margin-top: 0; margin-bottom: 0rem; text-align: center;">
Your password is not strong enough. New passwords must:
<li>Be at least minimum eight to maximum 16 characters long.</li>
<li>Contain one or more numbers.</li>
<li>With at least one small and one capital letter.</li>
<li>Include at least one special character like: [@#(/)+]</li>
</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
и если вышеприведенный код не выполняется, то покажите сообщение, приходящее из моего представления Django, которое написано следующим образом
<div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert">
<p style="margin-top: 0; margin-bottom: 0rem; text-align: center;" {% if message.tags %} {% endif %}>
{{ message }}
</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
условия сообщения от views.py file
if username_exists:
messages.warning(request, "Username is not available")
if email_exists:
messages.warning(request, "Email id is already registered")
if not pass_match:
messages.warning(request, "Grr.. password does not match")
if not complex_pass(password):
# complex_pass is a function which returns
# Boolean value either user entered password is complex or not
messages.warning(request, "password not strong enough")
Проблема заключается в условии if-else в моем Django template
Во время, когда условие: message == "password not strong enough"
является True
, я ожидаю, что вместо отображения "password not strong enough"
будет отображаться другой фрагмент HTML кода, но в моем случае, вместо фрагмента HTML кода отображается только сообщение django.
Вот полный HTML код с if-else
условием
{% if messages %}
{% for message in messages %}
{% if message == "password not strong enough" %}
<div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert">
<p style="margin-top: 0; margin-bottom: 0rem; text-align: center;">
Your password is not strong enough. New passwords must:
<li>Be at least minimum eight to maximum 16 characters long.</li>
<li>Contain one or more numbers.</li>
<li>With at least one small and one capital letter.</li>
<li>Include at least one special character like: [@#(/)+]</li>
</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% else %}
<div class="alert alert-danger alert-dismissible fade show" style="margin-bottom: 0; font-size: 13px; margin-top: 0;" role="alert">
<p style="margin-top: 0; margin-bottom: 0rem; text-align: center;" {% if message.tags %} {% endif %}>
{{ message }}
</p>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
{% endfor %}
{% endif %}
Попробуйте изменить это:
messages.warning(request, "password not strong enough")
К этому:
messages.warning(request, '''<p style="margin-top: 0; margin-bottom: 0rem; text-align: center;">
Your password is not strong enough. New passwords must:
<li>Be at least minimum eight to maximum 16 characters long.</li>
<li>Contain one or more numbers.</li>
<li>With at least one small and one capital letter.</li>
<li>Include at least one special character like: [@#(/)+]</li>
</p>''', extra_tags='safe')
Тогда измените свой {{ message }}
на такой:
{% if 'safe' in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}
Вы не можете проверить message
на строку с помощью ==
, потому что она сама не является строкой.
Если вы загрузите сообщение в представление, а затем выведете его тип, например:
messages.info(request, "password not strong enough")
storage = messages.get_messages(request)
for message in storage:
print(type(message))
будет напечатано:
<class 'django.contrib.messages.storage.base.Message'>
Так что это не строка.
.
Но простое приведение к строке, как это: if str(message) == "password not strong enough":
будет работать.
Очевидно, что мы хотим, чтобы это работало в шаблоне, и для этого вы можете использовать встроенный фильтр stringformat
.
Поэтому просто замените оператор if в вашем html-шаблоне на следующий:
{% if message|stringformat:"s" == "password not strong enough" %}