【问题标题】:why error_messages doesn't working in Meta class?为什么 error_messages 在 Meta 类中不起作用?
【发布时间】:2022-06-17 01:32:21
【问题描述】:

我的表单.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 中的任何错误而发生?

当我在定义时使用它时它正在工作:

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

【问题讨论】:

    标签: python django django-models django-forms


    【解决方案1】:

    来自[Django-doc]

    自动生成的字段取决于 Meta 类的内容以及已经以声明方式定义的字段。基本上,ModelForm 只会生成表单中缺少的字段,或者换句话说,未以声明方式定义的字段。

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

    以声明方式定义的字段保持原样,因此对 Meta 属性(如小部件、标签、help_texts 或 error_messages)所做的任何自定义都将被忽略;这些仅适用于自动生成的字段。

    这就是Meta类的error_messages属性得到ignored的原因。

    当我在定义时使用它时它正在工作:

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

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

    【讨论】:

      猜你喜欢
      • 2014-04-11
      • 2011-08-28
      • 2016-12-12
      • 2011-07-03
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      相关资源
      最近更新 更多