如何为 ModelFormMixin 覆盖 clean 和 clean_fieldname
How to overwrite clean and clean_fieldname for ModelFormMixin
我找到了这个
How to properly overwrite clean() method
还有这个
Can `clean` and `clean_fieldname` methods be used together in Django ModelForm?
但如果使用通用 class mixin ModelFormMixin
.
,它的工作方式似乎会有所不同
我的class也是从ProcessFormView
派生出来的。
def form_valid(self, form):
是我可以覆盖表单处理过程的唯一点吗?
您混淆了视图和表单。例如,CreateView
使用 ModelForm
来创建一个对象。但是,您可以自己指定这种形式,然后将其作为 form_class
传递给视图,而不是让视图构造 ModelForm
。
例如,假设您有一个带有 name
字段的 Category
模型,并且您希望验证 Category
的名称是否全部以小写形式书写,您可以定义ModelForm
这样做:
from django import forms
from django.core.exceptions import ValidationError
class CategoryForm(forms.ModelForm):
def <strong>clean_name</strong>(self):
data = self.cleaned_data['recipients']
if not data.islower():
raise ValidationError('The name of the category should be written in lowercase')
return data
class Meta:
model = Category
fields = ['name']
现在我们可以插入 ModelForm
作为我们 CategoryCreateView
:
的形式
from django.views.generic import CreateView
class CategoryCreateView(CreateView):
model = Category
<strong>form_class = CategoryForm</strong>
因此应在 ModelForm
中完成验证,然后您可以在 CreateView
、UpdateView
等
中使用该表单
我找到了这个
How to properly overwrite clean() method
还有这个
Can `clean` and `clean_fieldname` methods be used together in Django ModelForm?
但如果使用通用 class mixin ModelFormMixin
.
,它的工作方式似乎会有所不同
我的class也是从ProcessFormView
派生出来的。
def form_valid(self, form):
是我可以覆盖表单处理过程的唯一点吗?
您混淆了视图和表单。例如,CreateView
使用 ModelForm
来创建一个对象。但是,您可以自己指定这种形式,然后将其作为 form_class
传递给视图,而不是让视图构造 ModelForm
。
例如,假设您有一个带有 name
字段的 Category
模型,并且您希望验证 Category
的名称是否全部以小写形式书写,您可以定义ModelForm
这样做:
from django import forms
from django.core.exceptions import ValidationError
class CategoryForm(forms.ModelForm):
def <strong>clean_name</strong>(self):
data = self.cleaned_data['recipients']
if not data.islower():
raise ValidationError('The name of the category should be written in lowercase')
return data
class Meta:
model = Category
fields = ['name']
现在我们可以插入 ModelForm
作为我们 CategoryCreateView
:
from django.views.generic import CreateView
class CategoryCreateView(CreateView):
model = Category
<strong>form_class = CategoryForm</strong>
因此应在 ModelForm
中完成验证,然后您可以在 CreateView
、UpdateView
等