Django custom error message

爷,独闯天下 提交于 2020-01-15 09:32:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!