python - Displaying validation error instead of default text errors in Django UserCreationForm
问题描述
I have a very simple registration form on my website. My form works, but if a username already exists or my 2 password fields don't match, after I submit the form, Django does not do anything and just focuses the field with the error.
Forms.py
class CreateUserForm(UserCreationForm):
username = forms.CharField(required=True, max_length=30)
email = forms.EmailField(required=True)
first_name = forms.CharField(required=True, max_length=50)
last_name = forms.CharField(required=True, max_length=50)
class Meta:
model = User
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2',]
If anyone needs any more details, feel free to let me know. Thank you to everyone who helps!
解决方案
If I understand you right, you can show errors from the form in your template. Something like this:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
{{ error|escape }}
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
Detailed documentation: https://docs.djangoproject.com/en/3.2/ref/forms/api/#django.forms.Form.errors
推荐阅读
- database-design - 在 3 个表之间建立关系
- java - Java CompletableFuture anyOf N
- c# - 我不断收到“无法在 DLL 'user32.dll' 中找到名为 'GetWindowLongPtrA' 的入口点”
- netlogo - 在 netlogo 中从 shapefile 添加障碍物和目标
- javascript - 我可以在多个事件侦听器中重用 javascript 函数吗?
- java - 我可以修改 maven-javadoc-plugin 2.10.4 生成的 Javadoc 注释吗?
- c# - MDi 背景图像使动画子窗体显得缓慢
- google-cloud-platform - 谷歌云虚拟机不能有高数据包/秒速率
- jquery - 如果需要输入,则将类添加到 div
- javascript - 如何解决在外部文件中使用 javascript 和在 html 中使用 javascript 的问题