Create Custom Error Messages with Model Forms

后端 未结 7 1908
一向
一向 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:21

    New in Django 1.6:

    ModelForm accepts several new Meta options.

    • Fields included in the localized_fields list will be localized (by setting localize on the form field).
    • The labels, help_texts and error_messages options may be used to customize the default fields, see Overriding the default fields for details.

    From that:

    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            fields = ('name', 'title', 'birth_date')
            labels = {
                'name': _('Writer'),
            }
            help_texts = {
                'name': _('Some useful help text.'),
            }
            error_messages = {
                'name': {
                    'max_length': _("This writer's name is too long."),
                },
            }
    

    Related: Django's ModelForm - where is the list of Meta options?

    0 讨论(0)
  • 2020-11-28 07:25

    For simple cases, you can specify custom error messages

    class AuthorForm(forms.ModelForm):
        first_name = forms.CharField(error_messages={'required': 'Please let us know what to call you!'})
        class Meta:
            model = Author
    
    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-11-28 07:27

    Another easy way of doing this is just override it in init.

    class AuthorForm(forms.ModelForm):
        class Meta:
            model = Author
    
        def __init__(self, *args, **kwargs):
            super(AuthorForm, self).__init__(*args, **kwargs)
    
            # add custom error messages
            self.fields['name'].error_messages.update({
                'required': 'Please let us know what to call you!',
            })
    
    0 讨论(0)
  • 2020-11-28 07:28

    You can easily check and put custom error message by overriding clean()method and using self.add_error(field, message):

    def clean(self):
        super(PromotionForm, self).clean()
        error_message = ''
        field = ''
        # reusable check
        if self.cleaned_data['reusable'] == 0:
            error_message = 'reusable should not be zero'
            field = 'reusable'
            self.add_error(field, error_message)
            raise ValidationError(error_message)
    
        return self.cleaned_data
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题