【问题标题】:How to show the errors in the template?如何显示模板中的错误?
【发布时间】:2022-01-07 13:48:04
【问题描述】:
使用 Django 做一个简单的项目,刚刚完成了登录/注册表单。我要做的是在用户没有以正确的方式做某事时显示错误(例如:不匹配密码)
我使用这个库from django.contrib.auth import authenticate, login, logout 完成了登录/注册表单,它做得很好。
如何在模板中显示错误?
【问题讨论】:
标签:
django
django-forms
django-authentication
【解决方案1】:
在你的views.py中导入消息
from django.contrib import messages
并像下面给出的那样使用它
def signUp(request):
# Code here
if (condition):
messages.error(request, "message")
这里,错误是消息标签,messages.error 函数的第二个参数是实际消息。
然后在你的 html 文件中运行这个 for 循环来显示错误
{% for message in messages %}
<div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert">
<strong>Message: </strong> {{message}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
有5个消息标签-