无法在注册模板中看到错误消息。姜戈

Unable to see error messages in registration template. Django

大家下午好,

希望你一切都好

我正在建立我的第一个网站,但遇到以下问题;当我尝试创建新用户时,如果用户输入了错误的数据,模板不会显示错误。有什么提示吗?

模板:

<form action= "" method='post'>
{% csrf_token %}
{% for field in form %}
<p>{{field.label}}{{field}}</p>       
{% endfor %}     
<button type="submit" class="btn btn-success">Create User</button>

Views.py:

def register_page(request):
form = UserForm
if request.method == 'POST':
    form = UserForm(request.POST)
    if form.is_valid():
        form.save()            
        return HttpResponseRedirect('http://127.0.0.1:8000/login_user/')  

context = {'form' : form}
return render(request, 'simple_investing/register.htm', context)

Forms.py:

class UserForm(UserCreationForm):
class Meta:
    model = User
    fields = ('username', 'email', 'password1', 'password2')

正如在 rendering fields manually section of the documentation 中所讨论的那样,对于您还应该呈现的字段 {{ field.errors }},以及 {{ form.non_field_errors }} 处理不特定于一种形式的错误。

因此模板应如下所示:

<form action= "" method="post">
  {% csrf_token %}
  {{ form<strong>.non_field_errors</strong> }}
  {% for field in form %}
    <p>
      {{ field<strong>.errors</strong> }}
      {{ field.label }}
      {{ field }}
    </p>
  {% endfor %}
  <button type="submit" class="btn btn-success">Create User</button>
</form>

该部分还讨论了如何枚举错误,并对这些错误应用特定的样式。