Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, Models & Forms: replace "This field is required" message

Tags:

forms

django

I know how to set my own custom error messages when using ordinary Django Forms. But what about Django Form based on an existing model? Consider following model and form:

Class MyModel(models.Model):
    name = models.CharField(max_length='30')

Class MyForm(forms.ModelForm):
    Class Meta:
        model = MyModel

If I create such form and try to post it, message "This field is required" appears. But how to change it? Of course I could do something like this:

Class MyForm(forms.ModelForm):
    model = forms.CharField(error_messages = {'required': "something..."})
    Class Meta:
        model = MyModel

But according to the documentation, max_length attribute won't be preserved and I have to write it explicitly to the form definition. I thought that the purpose of Model Forms is to avoid writing the same code twice. So there has to be some easy way to change the custom error message without rewriting the whole form. Basically it would be enough for me if my message looked something like "The field 'name' is required".

Please help.

like image 253
tobik Avatar asked Mar 21 '11 23:03

tobik


People also ask

What is MVT in Django?

Django, a Python framework to create web applications, is based on Model-View-Template (MVT) architecture. MVT is a software design pattern for developing a web application.

Should I use Django models?

When do you use a Django model? Use Django models when you need to dynamically load information in your project. For example, if you create a blog don't hard code every piece of article content. Create an article model with the article title, URL slug, and content as the model fields.

What is abstract model Django?

An abstract model is a base class in which you define fields you want to include in all child models. Django doesn't create any database table for abstract models. A database table is created for each child model, including the fields inherited from the abstract class and the ones defined in the child model.


1 Answers

class MyForm(forms.ModelForm):
    class Meta:
            model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['name'].error_messages = {'required': 'custom required message'}

        # if you want to do it to all of them
        for field in self.fields.values():
            field.error_messages = {'required':'The field {fieldname} is required'.format(
                fieldname=field.label)}
like image 50
Yuji 'Tomita' Tomita Avatar answered Nov 04 '22 08:11

Yuji 'Tomita' Tomita