Create Custom Error Messages with Model Forms

后端 未结 7 2000
一向
一向 2020-11-28 06:56

I can see how to add an error message to a field when using forms, but what about model form?

This is my test model:

class Author(models.Model):
             


        
7条回答
  •  孤城傲影
    2020-11-28 07:29

    the easyest way is to override the clean method:

    class AuthorForm(forms.ModelForm):
       class Meta:
          model = Author
       def clean(self):
          if self.cleaned_data.get('name')=="":
             raise forms.ValidationError('No name!')
          return self.cleaned_data
    

提交回复
热议问题