Django自定义错误消息 [英] Django custom error message

查看:143
本文介绍了Django自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用我的母语显示错误消息。
下面是来自4个不同试验的粘贴代码,它们都不起作用
我发现的所有方法都不起作用

解决方案

您可以尝试通过向小部件添加属性来禁用它:

  forms.EmailField(widget = forms.EmailInput(attrs = {'novalidate':''}),required = True,error_messages = {'required': custom})


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>  

解决方案

you can try to disable by add attribute to the widget:

forms.EmailField(widget=forms.EmailInput(attrs={'novalidate':''}), required=True, error_messages = {'required': "custom"})

这篇关于Django自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆