0
是什麼用的區別:使用字段屬性和在Django CreateView中使用FormClass有什麼區別?
class FooCreateView(CreateView):
model = Foo
fields = (f,o,o)
和
class FooCreateView(CreateView):
model = Foo
form_class = FooForm
是什麼用的區別:使用字段屬性和在Django CreateView中使用FormClass有什麼區別?
class FooCreateView(CreateView):
model = Foo
fields = (f,o,o)
和
class FooCreateView(CreateView):
model = Foo
form_class = FooForm
不同的是,在第二個需要定義一個FooForm
類必須從Django的ModelForm
類繼承,並有model = Foo
,這種機制可以讓你在你的形式實現額外的驗證(通過定義類似的方法,即:def clean_f(self)
,def clean_o(self)
)
正如你所看到的,你不需要在CreateView
subclasss指定fields
屬性,如果使用form_class,因爲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
如果您嘗試保存不包含在他們的˚F屬性的「M」一個Foo實例這將引發ValidationError。
完整的答案,謝謝,但如果我只是想用'form_valid'和'form_invalid'方法哪一種是最好的做法,使用'fields'或'form_class'? (我知道是另一個問題,但過於簡單的創建一個新的) – arcegk
我想避免'form_class'。 – slackmart
@slackmart我的模型場'start_date',我試圖定義,比如'高清clean_start_date(個體經營)功能:'但控制不能走這條函數內。 –