为什么 error_messages 在 Meta class 中不起作用?

why error_messages doesn't working in Meta class?

我的forms.py

from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django import forms
from . models import Detail

class DetailForm(ModelForm):
name = forms.CharField(validators=[not_contain_number], required=True)
email = forms.EmailField(required=True)
phone_no = forms.IntegerField(
    validators=[number_validation], required=True)
class Meta:
    model = Detail
    error_messages = {
        'name': {
            'required': 'enter your name',
        },
    }
    labels = {'name': 'Your Name', 'email': 'Your Email',
              'phone_no': 'Your Phone No.'}
    widgets = {'name': forms.TextInput(
        attrs={'placeholder': 'type your Name'})}
    fields = ['name', 'email', 'phone_no']

是否是我在ModelForm中的任何错误导致的API?

It is working when i used it while defining:

class DetailForm(ModelForm):
        name = forms.CharField(validators=[not_contain_number], required=True,error_messages={'required': 'Enter Your Name'})

来自[Django-doc]

The fields that are automatically generated depend on the content of the Meta class and on which fields have already been defined declaratively. Basically, ModelForm will only generate fields that are missing from the form, or in other words, fields that weren’t defined declaratively

属性小部件、标签、help_texts或error_messages仅适用于引用

时自动生成的字段

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

这就是为什么 Meta class 的 error_messages 属性得到 ignored 的原因。

It is working when i used it while defining:

是的,您可以将 error_messages 定义为 class 属性,如您定义的

class DetailForm(ModelForm):
    name = forms.CharField(validators=[not_contain_number], required=True,error_messages={'required': 'Enter Your Name'})