详细代码:
形式:
class TrainingExpForm(BaseModelForm):
company_type = forms.ChoiceField(choices=COMPANY_TYPE_CHOICE)
company = forms.CharField(label=u'your company', required=True)
def __init__(self, *args, **kwargs):
super(TrainingExpForm, self).__init__(*args, **kwargs)
self.fields['exp_type'].initial = 'T'
# redefine order, because extra field 'company_type' can not write in Meta.fields
self.fields.keyOrder = ('exp_type', 'company_type', 'company', 'name', 'start_date', 'end_date', 'description')
def clean_exp_type(self):
exp_type = self.cleaned_data.get('exp_type')
if not exp_type:
self.cleaned_data['exp_type'] = self.initial['exp_type']
class Meta:
model = Experience
fields = ('exp_type', 'company', 'name', 'start_date', 'end_date', 'description')
widgets = {
'exp_type': HiddenInput(),
}
def get_exp_form(exp_type):
return WorkExpForm if exp_type =='W' else TrainingExpForm
的观点:
def exp_manage(request, exp_type, id=None):
if id:
exp = Experience.objects.get(id=id)
else:
exp = None
ExpForm = get_exp_form(exp_type)
if request.method == 'POST':
form = ExpForm(request.POST, instance=exp)
if form.is_valid():
return http.HttpResponseRedirect(reverse('zhemei_resume_manage'))
else:
form = ExpForm(instance=exp)
我在第if form.is_valid():
行设置了断点。
>>> request.POST.get('exp_type')
u'T'
>>> form.data.get('exp_type')
u'T'
>>> form.errors
{'exp_type': [u'can not be null']}
我无法理解上面的结果。我还试图找出django form
生成form.errors
的方式。但我无法在django源中找到相关代码
有人可以帮忙吗?
答案 0 :(得分:0)
clean_xxx方法must返回字段值:
def clean_exp_type(self):
exp_type = self.cleaned_data.get('exp_type')
if not exp_type:
exp_type = self.initial['exp_type']
return exp_type