【问题标题】:Django - strange dictionary behaviourDjango - 奇怪的字典行为
【发布时间】:2014-03-08 10:06:02
【问题描述】:

我正在尝试覆盖我的 Django 表单中的默认错误消息:

class RegistrationForm(forms.Form):

    my_errors = {
        'required': 'To pole jest wymagane'
    }
    email = forms.EmailField(max_length=254, error_messages=my_errors.update({'invalid': 'Podaj prawidłowy adres e-mail'}))
    password = forms.CharField(error_messages=my_errors)
    firstname = forms.CharField(max_length=80, error_messages=my_errors)
    lastname = forms.CharField(max_length=80, error_messages=my_errors)

    def clean_email(self):
        email = self.cleaned_data['email']
        User = get_user_model
        try:
            User.objects.get(email=email)
            raise forms.ValidationError('Adres e-mail jest już zajęty')
        except User.DoesNotExist:
            return email

我可以轻松更改“必填”错误消息,因为每个字段都相同。

但对于电子邮件字段,我希望“无效”消息更具体,因此我将现有字典与包含电子邮件错误消息的字典合并。

但它不起作用:电子邮件字段返回默认错误消息,而其余字段使用我的错误消息。

请解释为什么会发生以及如何解决它,谢谢

【问题讨论】:

    标签: python django dictionary


    【解决方案1】:

    dict.update 就地修改字典,并返回None。因此,您在声明 email 字段时传递了 error_messages=None

    您的代码的另一个不良副作用是"invalid" 被添加到my_errors,并且在声明其余字段时传递了扩展my_errors

    您需要合并字典而不是使用update,例如:

    class RegistrationForm(forms.Form):
    
        my_errors = {
            'required': 'To pole jest wymagane'
        }
        email = forms.EmailField(max_length=254, error_messages=dict(my_errors, invalid='Podaj prawidłowy adres e-mail'))
        password = forms.CharField(error_messages=my_errors)
        ...
    

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多