Create Custom Error Messages with Model Forms

后端 未结 7 1909
一向
一向 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:43

    I have a cleaner solution, based on jamesmfriedman's answer. This solution is even more DRY, especially if you have lots of fields.

    custom_errors = {
        'required': 'Your custom error message'
    }
    
    class AuthorForm(forms.ModelForm):
        class Meta:
            model = Author
    
        def __init__(self, *args, **kwargs):
            super(AuthorForm, self).__init__(*args, **kwargs)
    
            for field in self.fields:
                self.fields[field].error_messages = custom_errors
    
    0 讨论(0)
提交回复
热议问题