以下是我的模型.py中的内容:
class GraduationApp(models.Model):
id = models.AutoField(primary_key=True)
addr_to_photographer = models.NullBooleanField(blank=True, null=True)
class Meta:
db_table = u'graduation_app'
这是我的表格
BOOLEAN_CHOICES = (
(None,' '),
(True,'Yes'),
(False,'No')
)
class EnterAppForm(ModelForm):
addr_to_photographer = forms.ChoiceField(choices=BOOLEAN_CHOICES, required=False)
class Meta:
model = GraduationApp
fields=('addr_to_photographer')
以下是我的模板:
Address to Photographer? {{ form.addr_to_photographer }}
这是我在视图中的保存。py:
print 'your POST address_to_photographer is', request.POST['addr_to_photographer']
print 'your form.cleaned_data addr_to_photographer is', form.cleaned_data['addr_to_photographer']
updapp = GraduationAppForm.objects.get(id=request.POST['app_id'])
updapp.addr_to_photographer = form.cleaned_data['addr_to_photographer']
updapp.save()
print 'YOU JUST UPDATED ME', updapp.person.eid, 'ADDR TO PHOTO IS', updapp.addr_to_photographer
我收到这些打印报表:
您的POST地址_to_photographer为False
您的表单.cleand_data addr_to_photographer为False
你刚刚更新了我的oy278照片地址是(u'False',)
但当我查看MySQL中的字段时,它有一个1,而不是0。救命!
如果将选择移动到模型字段定义,会发生什么
您可以跳过表单中的重复字段声明:
models.py:
BOOLEAN_CHOICES = (
(None,' '),
(True,'Yes'),
(False,'No')
)
class GraduationApp(models.Model):
id = models.AutoField(primary_key=True)
addr_to_photographer = models.NullBooleanField(choices=BOOLEAN_CHOICES, blank=True, null=True)
class Meta:
db_table = u'graduation_app'
forms.py:
class EnterAppForm(ModelForm):
class Meta:
model = GraduationApp
解决方案是这样的:在更新时,我需要获得我需要更新的记录的无形部分,然后我需要用我的发布数据填充我的表单,并引用我的记录的实例。
updapp = GraduationApp.objects.get(id=request.POST['app_id'])
form = EnterAppForm(request.POST,instance=updapp)
事实上,我的表格里什么都不需要。除了这个:
class EnterAppForm(ModelForm):
class Meta:
model = GraduationApp
fields=('status','name_in_pgm','addr_to_photographer','paper_form_reason_1','paper_form_reason_2','notes',
'transfer_work_on_transcript','cbe_work_on_transcript','enrolled_other_institution',
'enrolled_correspondence','getting_degree_other_ut_college','understand_min_gpa_req',
'understand_no_drop_req','understand_pass_fail_req','understand_deg_requirements',
'address_verified','eligibility_confirmed','placement_survey_complete')