问题
I want to display error messages in my native language. Below pasted code from 4 different trials and none of them worked None of the methods I found were not working Django, Models & Forms: replace "This field is required" message
forms.py
class UserCreateForm(UserCreationForm):
email = forms.EmailField(required=True, error_messages = {'required': "custom"})
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2", "first_name", "last_name")
error_messages = {
'unique_together': "custom",
'blank': "custom",
'null': "custom",
}
def __init__(self, *args, **kwargs):
super(UserCreateForm, self).__init__(*args, **kwargs)
self.fields['email'].error_messages = {'required': 'custom'}
# if you want to do it to all of them
for field in self.fields.values():
field.error_messages = {'required':'custom {fieldname} custom'.format(
fieldname=field.label)}
views.py
def signup(request, string, step):
if request.POST:
user_form = UserCreateForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
Profile.objects.create(**{
'city':request.POST['city'], 'phone': request.POST['phone'], 'isStudent': istudent, 'emailnotafications': request.POST.get('emailnotafications', False), 'user': user
})
...
template
<div class="form-group field-user-username required">
<label class="control-label" for="user-username">Email</label>
{{ user_form.email |add_class:"form-control" }}
</div>
<div class="form-group field-user-username required">
<label class="control-label" for="user-username">Hasło</label>
{{ user_form.password1 |add_class:"form-control" }}
</div>
回答1:
you can try to disable by add attribute to the widget:
forms.EmailField(widget=forms.EmailInput(attrs={'novalidate':''}), required=True, error_messages = {'required': "custom"})
来源:https://stackoverflow.com/questions/45824090/django-custom-error-message