我想在 django 表单中有自己的错误,但我不能。如您所见,我定义了自己的 error_messages 但 django 仍在使用它自己的错误。
应用账户/forms.py:
from django import forms
error_messages_email = {
'required': 'please Fill-out this field',
'invalid': 'invalid format for email',
'max_length': 'max length is 40 chars',
}
error_messages = {
'required': 'please Fill-out this field',
'invalid': 'fields format is not valid',
'max_length': 'max_length is 30 chars',
'min_length': 'password should be at least 8 Chars',
}
class LoginForm(forms.Form):
username = forms.CharField(error_messages=error_messages, max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control',
'placeholder': 'Username'}))
password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
widget=forms.PasswordInput(attrs={'class': 'form-control',
'placeholder': 'Password'}))
class SignupForm(forms.Form):
username = forms.CharField(error_messages=error_messages, max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control',
'placeholder': 'Username'}))
email = forms.EmailField(error_messages=error_messages_email, max_length=40,
widget=forms.EmailInput(attrs={'class': 'form-control',
'placeholder': 'Email'}))
password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
widget=forms.PasswordInput(attrs={'class': 'form-control',
'placeholder': 'Password'}))
这是我的应用程序模板/signup.html:
{% extends 'main.html' %}
{% block title %} Join {% endblock %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.username.errors }}
<label for="{{ form.username.id_for_label }}">Username:</label>
{{ form.username }}<br>
{{ form.email.errors }}
<label for="{{ form.email.id_for_label }}">E-mail:</label>
{{ form.email }}<br>
{{ form.password.errors }}
<label for="{{ form.password.id_for_label }}">Password:</label>
{{ form.password }}<br>
<input type="submit" value="signup" class="btn btn-primary" >
</form>
{% endblock %}
唯一的问题是其他部分作业正常的错误,在浏览器中我还将 max_length 更改为 50 并传递一个 50 字符的密码并提交它,它作业正常并显示我自己的错误。
uj5u.com热心网友回复:
您只能将error_messages
关键字自变量用于 aModel
或 a ModelForm
。
由于您只是使用标准,Form
因此不会呈现您期望的行为。
您需要将您的更改LoginForm
为继承ModelForm
。例如:
class LoginForm(forms.ModelForm):
username = forms.CharField(error_messages=error_messages, max_length=30,
widget=forms.TextInput(attrs={'class': 'form-control',
'placeholder': 'Username'}))
password = forms.CharField(error_messages=error_messages, min_length=8, max_length=30,
widget=forms.PasswordInput(attrs={'class': 'form-control',
'placeholder': 'Password'}))
class Meta:
model=User
fields = ('username','password')
0 评论