Yousef
Yousef

Reputation: 75

Django error message in class based view

Can I change the error message from the model for a class-based view? the following is not working, it always gives the default message from Django.

Model:

class Child(models.Model):
   name = models.CharField(max_length=100, error_messages={ 'blank': 'cannot be blank or null', 'null': 'cannot be blank or null',})

view:

class ChildCreate(CreateView):
  model = Child
  fields = '__all__'
  success_url = reverse_lazy('children-list')

Upvotes: 0

Views: 1574

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

From the docs:

Error messages defined at the form field level or at the form Meta level always take precedence over the error messages defined at the model field level.

So you can create model form and add required error message there:

class ChildForm(forms.ModelForm):
    use_required_attribute = False

    class Meta:
        model = models.Child
        fields = '__all__'
        error_messages = {'name': {'required': 'cannot be blank or null'}} 

class ChildCreate(CreateView):
    model = Child
    form_class = forms.ChildForm
    success_url = reverse_lazy('children-list')

Upvotes: 1

Related Questions