在 Django CreateView 中使用字段属性和使用 FormClass 有什么区别?
What is the difference between use fields attribute and use a FormClass in Django CreateView?
使用上有什么区别:
class FooCreateView(CreateView):
model = Foo
fields = (f,o,o)
和
class FooCreateView(CreateView):
model = Foo
form_class = FooForm
不同的是,在第二个你需要定义一个FooForm
class,它必须继承自Django ModelForm
class并且有一个model = Foo
,此机制允许您对表单实施额外验证(即通过定义方法,例如:def clean_f(self)
、def clean_o(self)
)
如您所见,如果使用 form_class,则无需在 CreateView
子 class 中指定 fields
属性,因为 Django 会获取 form_class
字段并使用它。
示例:
models.py
from django.db import models
class Foo(models.Model):
f = models.CharField(max_length=10)
forms.py
from django import forms
from appname.models import Foo
class FooForm(forms.ModelForm):
class Meta:
model = Foo
fields = '__all__' # shortcut to add all Foo fields.
def clean_f(self):
if 'M' not in self.cleaned_data['f']:
raise forms.ValidationError('M char must be in f attribute')
return self.cleaned_data['f']
views.py
from django.views.edit import CreateView
from appname.forms import FooForm
class FooCreateView(CreateView):
model = Foo
form_class = FooForm
如果您尝试保存 Foo 实例,而该实例的 f 属性中不包含 'M',这将引发 ValidationError。
使用上有什么区别:
class FooCreateView(CreateView):
model = Foo
fields = (f,o,o)
和
class FooCreateView(CreateView):
model = Foo
form_class = FooForm
不同的是,在第二个你需要定义一个FooForm
class,它必须继承自Django ModelForm
class并且有一个model = Foo
,此机制允许您对表单实施额外验证(即通过定义方法,例如:def clean_f(self)
、def clean_o(self)
)
如您所见,如果使用 form_class,则无需在 CreateView
子 class 中指定 fields
属性,因为 Django 会获取 form_class
字段并使用它。
示例:
models.py
from django.db import models
class Foo(models.Model):
f = models.CharField(max_length=10)
forms.py
from django import forms
from appname.models import Foo
class FooForm(forms.ModelForm):
class Meta:
model = Foo
fields = '__all__' # shortcut to add all Foo fields.
def clean_f(self):
if 'M' not in self.cleaned_data['f']:
raise forms.ValidationError('M char must be in f attribute')
return self.cleaned_data['f']
views.py
from django.views.edit import CreateView
from appname.forms import FooForm
class FooCreateView(CreateView):
model = Foo
form_class = FooForm
如果您尝试保存 Foo 实例,而该实例的 f 属性中不包含 'M',这将引发 ValidationError。