Saleh
Saleh

Reputation: 294

customize error message 'please fill out this form' in Django

I have written this function in Django to override the 'label suffix and form field error message. Within the same function, the lebel suffix is working (the colon is removed) but the error message did not replaced by with customized one. Here is the form class with the function:

class User_accountModelForm(forms.ModelForm):

    # to remove colons from the labels:
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(User_accountModelForm, self).__init__(*args, **kwargs)

        # changing error messages:
        for field in self.fields.values():
        field.error_messages = {'required':'The field {fieldname} is required'.format(fieldname=field.label)}



    class Meta:
        model = User_account
        fields = ['first_name', 'other fields']

any help or clue is appreciated

Upvotes: 1

Views: 1630

Answers (1)

Ralf
Ralf

Reputation: 16505

To override the forms error messages, add it to the forms Meta; see also the ModelForm docs:

class User_accountModelForm(ModelForm):
    class Meta:
        model = User_account
        fields = ['first_name', 'other fields']
        error_messages = {
            'first_name': {
                # for example:
                'max_length': _("This writer's name is too long."),
            },
        }

Upvotes: 1

Related Questions