如何在Django中的模型上使用error_messages

时间:2021-03-27 07:24:29

I understand form the documentation http://docs.djangoproject.com/en/dev/ref/models/fields/ that you can add error_messages to a model field and supply your own dict of error messages. However, what are they keys of the dict you are supposed to pass?

我理解文档http://docs.djangoproject.com/en/dev/ref/models/fields/,您可以将error_messages添加到模型字段并提供您自己的错误消息字典。但是,你应该通过的词典的关键是什么?

class MyModel(models.Model):
   some_field = models.CharField(max_length=55, error_messages={'required': "My custom error"})

If it is easier to do this on the modelform that is used that would also work, however. I would rather not have to create explicitly creating each field and their type again. This is what I was trying to avoid:

但是,如果在使用的模型表格上执行此操作更容易,也可以使用。我宁愿不必再创建显式创建每个字段及其类型。这是我试图避免的:

class MyModelForm(forms.ModelForm):
    some_field = forms.CharField(error_messages={'required' : 'Required error'})

Update 2: Test code used in my project

更新2:我的项目中使用的测试代码

My Model:

class MyTestModel(models.Model):
    name = models.CharField(max_length=127,error_messages={'blank' : 'BLANK','required' : 'REQUIRED'})

My Form:

class EditTestModel(ModelForm):
    class Meta:
        model = MyTestModel

My View:

tf = EditTestModel({'name' : ''})

print tf.is_valid() # prints False
print tf.full_clean() # prints None
print tf # prints the form, with a <li> error list containg the error "This field is required"


<tr><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_name" type="text" name="name" maxlength="127" /></td></tr>

3 个解决方案

#1


5  

You're right, those docs are not very useful. It's a recent addition after all!

你没错,那些文档不是很有用。毕竟这是最近添加的!

My guess is that the normal usage of error_messages is for ModelForms, so I'd look here for a list of acceptable error keys per field: http://docs.djangoproject.com/en/dev/ref/forms/fields/#error-messages

我的猜测是error_messages的正常用法是针对ModelForms的,所以我在这里查看每个字段可接受的错误键列表:http://docs.djangoproject.com/en/dev/ref/forms/fields/#错误信息

But, if you want to be really safe and not assume anything...

但是,如果你想要真正安全而不承担任何责任......

The most reliable way for now is going to be looking at the source at django/db/models/fields/__init__.py where you'll see each of the default_error_messages that can be specified and the actual calls to self.error_messages['invalid']

现在最可靠的方法是查看django / db / models / fields / __ init__.py中的源代码,在那里你可以看到每个可以指定的default_error_messages以及对self.error_messages的实际调用['无效“]

# Field (base class)

default_error_messages = {
    'invalid_choice': _(u'Value %r is not a valid choice.'),
    'null': _(u'This field cannot be null.'),
    'blank': _(u'This field cannot be blank.'),
}

# AutoField  
    default_error_messages = {
        'invalid': _(u'This value must be an integer.'),
    }

Here's the doc on model validation: http://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

这是关于模型验证的文档:http://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

Update:

Just tested this in a shell session and it appears to be working. Whats up?

刚刚在shell会话中对此进行了测试,它似乎正在运行。这是怎么回事?

I just defined a simple model:

我刚刚定义了一个简单的模型:

class SubscriptionGroup(models.Model):
    name = models.CharField(max_length=255, error_messages={'blank': 'INVALID!!11', 'null': 'NULL11!'})

# shell
>>> s = SubscriptionGroup()
>>> s.full_clean()
ValidationError: {'name': [u'INVALID!!11']}

#2


3  

(Bit late to this one, but I have been through the same issues myself, so using this as a note_to_self as much as anything.)

(这一点迟到了,但我自己也经历过同样的问题,因此将其作为note_to_self使用它。)

You can specify error_messages on both models and modelforms. The keys you should / can use are defined here for the form fields. The issue seems to be (to me) the inter-relationship between forms and the related model, and which error message appears, and when. The key to this is understanding that forms and models are actually very loosely-coupled, and that there really is no magic happening.

您可以在模型和模型上指定error_messages。您应该/可以使用的键在此处为表单字段定义。问题似乎是(对我而言)表单和相关模型之间的相互关系,以及出现的错误消息以及何时出现。关键在于理解形式和模型实际上是非常松散耦合的,并且确实没有神奇的事情发生。

If you have a model field called 'quote', with a max_length of 140, and a modelform associated with this model, the error messages will work thus:

如果您有一个名为'quote'的模型字段,其max_length为140,并且该模型与该模型相关联,则错误消息将起作用:

  • If you don't explicitly add a max_length attribute to the modelform, and then validate the form (calling is_valid() or errors), the error message that comes back will be from the model.
  • 如果没有向modelform显式添加max_length属性,然后验证表单(调用is_valid()或errors),则返回的错误消息将来自模型。

  • If you add a set of error_messages ('required','max_length') to the model, these will appear in the errors collection.
  • 如果向模型添加一组error_messages('required','max_length'),它们将出现在errors集合中。

  • If you add a set of error_messages to the modelform, they will not appear, as it is the model that is failing validation, not the form.
  • 如果向模型表单添加一组error_messages,它们将不会出现,因为它是验证失败的模型,而不是表单。

  • If you then add a max_length attribute to the modelform, you will see the modelform errors surfacing (and overriding the model error_messages.)
  • 如果然后将max_length属性添加到modelform,您将看到模型表单错误浮出水面(并覆盖模型error_messages。)

So - fairly simple in summary - the error messages map to the object that is being validated - which can be either the model or the modelform.

所以 - 总结起来相当简单 - 错误消息映射到正在验证的对象 - 可以是模型或模型。

#3


2  

I tried. It will not work if you defined it in models. You must define error_messages in your forms like this

我试过了。如果您在模型中定义它将无法工作。您必须在表单中定义error_messages,如下所示

name = forms.CharField(error_messages={'required': 'this field is required'})

#1


5  

You're right, those docs are not very useful. It's a recent addition after all!

你没错,那些文档不是很有用。毕竟这是最近添加的!

My guess is that the normal usage of error_messages is for ModelForms, so I'd look here for a list of acceptable error keys per field: http://docs.djangoproject.com/en/dev/ref/forms/fields/#error-messages

我的猜测是error_messages的正常用法是针对ModelForms的,所以我在这里查看每个字段可接受的错误键列表:http://docs.djangoproject.com/en/dev/ref/forms/fields/#错误信息

But, if you want to be really safe and not assume anything...

但是,如果你想要真正安全而不承担任何责任......

The most reliable way for now is going to be looking at the source at django/db/models/fields/__init__.py where you'll see each of the default_error_messages that can be specified and the actual calls to self.error_messages['invalid']

现在最可靠的方法是查看django / db / models / fields / __ init__.py中的源代码,在那里你可以看到每个可以指定的default_error_messages以及对self.error_messages的实际调用['无效“]

# Field (base class)

default_error_messages = {
    'invalid_choice': _(u'Value %r is not a valid choice.'),
    'null': _(u'This field cannot be null.'),
    'blank': _(u'This field cannot be blank.'),
}

# AutoField  
    default_error_messages = {
        'invalid': _(u'This value must be an integer.'),
    }

Here's the doc on model validation: http://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

这是关于模型验证的文档:http://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

Update:

Just tested this in a shell session and it appears to be working. Whats up?

刚刚在shell会话中对此进行了测试,它似乎正在运行。这是怎么回事?

I just defined a simple model:

我刚刚定义了一个简单的模型:

class SubscriptionGroup(models.Model):
    name = models.CharField(max_length=255, error_messages={'blank': 'INVALID!!11', 'null': 'NULL11!'})

# shell
>>> s = SubscriptionGroup()
>>> s.full_clean()
ValidationError: {'name': [u'INVALID!!11']}

#2


3  

(Bit late to this one, but I have been through the same issues myself, so using this as a note_to_self as much as anything.)

(这一点迟到了,但我自己也经历过同样的问题,因此将其作为note_to_self使用它。)

You can specify error_messages on both models and modelforms. The keys you should / can use are defined here for the form fields. The issue seems to be (to me) the inter-relationship between forms and the related model, and which error message appears, and when. The key to this is understanding that forms and models are actually very loosely-coupled, and that there really is no magic happening.

您可以在模型和模型上指定error_messages。您应该/可以使用的键在此处为表单字段定义。问题似乎是(对我而言)表单和相关模型之间的相互关系,以及出现的错误消息以及何时出现。关键在于理解形式和模型实际上是非常松散耦合的,并且确实没有神奇的事情发生。

If you have a model field called 'quote', with a max_length of 140, and a modelform associated with this model, the error messages will work thus:

如果您有一个名为'quote'的模型字段,其max_length为140,并且该模型与该模型相关联,则错误消息将起作用:

  • If you don't explicitly add a max_length attribute to the modelform, and then validate the form (calling is_valid() or errors), the error message that comes back will be from the model.
  • 如果没有向modelform显式添加max_length属性,然后验证表单(调用is_valid()或errors),则返回的错误消息将来自模型。

  • If you add a set of error_messages ('required','max_length') to the model, these will appear in the errors collection.
  • 如果向模型添加一组error_messages('required','max_length'),它们将出现在errors集合中。

  • If you add a set of error_messages to the modelform, they will not appear, as it is the model that is failing validation, not the form.
  • 如果向模型表单添加一组error_messages,它们将不会出现,因为它是验证失败的模型,而不是表单。

  • If you then add a max_length attribute to the modelform, you will see the modelform errors surfacing (and overriding the model error_messages.)
  • 如果然后将max_length属性添加到modelform,您将看到模型表单错误浮出水面(并覆盖模型error_messages。)

So - fairly simple in summary - the error messages map to the object that is being validated - which can be either the model or the modelform.

所以 - 总结起来相当简单 - 错误消息映射到正在验证的对象 - 可以是模型或模型。

#3


2  

I tried. It will not work if you defined it in models. You must define error_messages in your forms like this

我试过了。如果您在模型中定义它将无法工作。您必须在表单中定义error_messages,如下所示

name = forms.CharField(error_messages={'required': 'this field is required'})