我非常喜欢django初学者,所以也许这应该是显而易见的:
在Python 2.7上使用django 1.6,我有几个模型,如下所示:
class Pad_info(models.Model):
site_id = models.IntegerField(primary_key=True)
name = models.CharField('Pad Location', max_length=40, unique=True)
area_worked = models.DecimalField(max_digits=12, decimal_places=2)
....
def __unicode__(self):
return u'%s %s' % (self.site_id, self.name)
class Inspections(models.Model):
of_pad = models.ForeignKey(Pad_info)
insp_date = models.DateField('Inspection Date')
agency = models.CharField('Agency/ Organization', max_length=40)
lead_inspector = models.CharField('Lead Inspector', max_length=40)
accepted = models.BooleanField(default=False)
comments = models.TextField('Comments/ Notes')
我有一个表单类,其中包含Inspections类中具有相同名称的所有字段。
在我的观看中,我有一个显示表单并尝试使用输入表单字段的数据创建新记录:
def inspectioncreate_m(request):
if request.method == 'POST':
form = create_insp_m(request.POST)
if form.is_valid():
insp_date = form.cleaned_data['insp_date']
of_pad = form.cleaned_data['of_pad']
agency = form.cleaned_data['agency']
lead_inspector = form.cleaned_data['lead_inspector']
accepted = form.cleaned_data['accepted']
comments = form.cleaned_data['comments']
# find if there is a record that matches pad_id
try:
checkPad = Pad_info.objects.get(pk=of_pad)
newrecord = Inspections(of_pad, insp_date, agency, lead_inspector, accepted,
comments)
newrecord.save(force_insert=True)
except Pad_info.DoesNotExist:
....
表单和模板很好地显示," of_pad"字段显示由" site_id"组成的选项列表。和"名称" Pad_info类的组合。这对于显示父记录的选择很有用。在特殊情况下,我正在努力争取父母的“site_id”和“#s;' site_id'是41,名字是" N. EZ Jr"。它们合并为选择列表中的单个字符串。但是当我保存新记录时,我希望它只提供父级的site_id,而不是来自父级的字符串' "自"属性。
我保存时遇到TypeError,因为现在of_pad变量包含" Pad_info:41 N. EZ Jr"。错误读取" int()参数必须是字符串或数字,而不是' Pad_info'"。
那么在这种情况下,我怎样才能获得' 41'作为父母的site_id?
的整数