In Django, how do i change “This field is required.” to “Name is required”?

前端 未结 2 563
忘了有多久
忘了有多久 2021-02-08 11:51

I\'m using the forms framework. And when I set required=True, this error shows. What if I don\'t want it to say \"This field\", but instead, say the label?

Since i\'m no

相关标签:
2条回答
  • 2021-02-08 12:17

    An easy way to specify simple "required" validation messages is to pass the field the error_messages argument.

    name = forms.CharField(error_messages={'required': 'Your Name is Required'}) 
    

    Check the docs for which keys can be specified per field: http://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.Field.error_messages

    For anything else, you're going to need real form validation which means you'd be writing error messages anyways!

    0 讨论(0)
  • 2021-02-08 12:40

    If you want to customize the message a little bit more you can also:

    from django.core.exceptions import ValidationError
    
    def my_validator(value):
        if not len(value):
            raise ValidationError('Your error message here!')
    

    Then, in your models.py:

    from django import forms
    
    class MyForm(forms.Form):
        my_field= forms.CharField(validators=[my_validator])
    
    0 讨论(0)
提交回复
热议问题