gpt4 book ai didi

python - 为什么 error_messages 在元类中不起作用?

转载 作者:行者123 更新时间:2023-12-05 05:47:41 24 4
gpt4 key购买 nike

我的表单.py

from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django import forms
from . models import Detail

class DetailForm(ModelForm):
name = forms.CharField(validators=[not_contain_number], required=True)
email = forms.EmailField(required=True)
phone_no = forms.IntegerField(
validators=[number_validation], required=True)
class Meta:
model = Detail
error_messages = {
'name': {
'required': 'enter your name',
},
}
labels = {'name': 'Your Name', 'email': 'Your Email',
'phone_no': 'Your Phone No.'}
widgets = {'name': forms.TextInput(
attrs={'placeholder': 'type your Name'})}
fields = ['name', 'email', 'phone_no']

是否是我在 ModelForm API 中的任何错误导致的?

It is working when i used it while defining:

class DetailForm(ModelForm):
name = forms.CharField(validators=[not_contain_number], required=True,error_messages={'required': 'Enter Your Name'})

最佳答案

来自 [Django-doc]

The fields that are automatically generated depend on the content of the Meta class and on which fields have already been defined declaratively. Basically, ModelForm will only generate fields that are missing from the form, or in other words, fields that weren’t defined declaratively.

widgets、labels、help_texts 或 error_messages 属性仅适用于按引用自动生成的字段:

Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically.

这就是 Meta 类的 error_messages 属性被忽略的原因。

It is working when i used it while defining:

是的,您可以将 error_messages 定义为您定义的类属性:

class DetailForm(ModelForm):
name = forms.CharField(validators=[not_contain_number], required=True,error_messages={'required': 'Enter Your Name'})

关于python - 为什么 error_messages 在元类中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70941263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com