why error_messages doesn't working in Meta class?

Viewed 1141

My 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']

Does it occurs due to my any mistake in 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'})
1 Answers

From [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.

The attributes widgets, labels, help_texts, or error_messages only works for fields generated automatically as quoted:

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.

That's the reason why error_messages attribute of Meta class got ignored.

It is working when i used it while defining:

Yes you can define error_messages as class attributes as defined by you as:

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