Create Custom Error Messages with Model Forms

后端 未结 7 2039
一向
一向 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:25

    I have wondered about this many times as well. That's why I finally wrote a small extension to the ModelForm class, which allows me to set arbitrary field attributes - including the error messages - via the Meta class. The code and explanation can be found here: http://blog.brendel.com/2012/01/django-modelforms-setting-any-field.html

    You will be able to do things like this:

    class AuthorForm(ExtendedMetaModelForm):
        class Meta:
            model = Author
            field_args = {
                "first_name" : {
                    "error_messages" : {
                        "required" : "Please let us know what to call you!"
                    }
                }
            }
    

    I think that's what you are looking for, right?

提交回复
热议问题