在Django中,如何更改“这个字段是必需的”。“名称是必需的”?

时间:2022-10-10 07:22:18

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?

我使用的是表单框架。当我设置required=True时,这个错误就会显示出来。如果我不想让它说“这个字段”,而是说标签呢?

Since i'm not going to be displaying it beneath the form input. I"m going to display all the errors at the top of the page.

因为我不会在表单输入下面显示它。我要把所有的错误都显示在这页的顶端。

2 个解决方案

#1


22  

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

指定简单的“required”验证消息的一种简单方法是传递error_messages参数。

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

检查每个字段可以指定哪些键:http://docs.djangoproject.com/en/dev/forms/fields/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!

对于其他任何东西,您都需要真正的表单验证,这意味着无论如何您都要编写错误消息!

#2


0  

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:

然后,在你的models.py:

from django import forms

class MyForm(forms.Form):
    my_field= forms.CharField(validators=[my_validator])

#1


22  

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

指定简单的“required”验证消息的一种简单方法是传递error_messages参数。

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

检查每个字段可以指定哪些键:http://docs.djangoproject.com/en/dev/forms/fields/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!

对于其他任何东西,您都需要真正的表单验证,这意味着无论如何您都要编写错误消息!

#2


0  

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:

然后,在你的models.py:

from django import forms

class MyForm(forms.Form):
    my_field= forms.CharField(validators=[my_validator])