clean_xxx method must return value of the field:
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
Frage
detail code:
form:
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
views:
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)
I have set a breakpoint at line: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']}
I can not understand what result to above .I have also tried to figure out how django form
generate form.errors
. But I just can't find the relevent code in django source.
Anyone can help?
Lösung
clean_xxx method must return value of the field:
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