我的表格:
class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
在模型中,所有者是配置文件的外键。
当我设置这个表单时,我将“owner”的值设置为一个 Profile 对象。
但是当它出现在表单上时,它似乎包含这样的配置文件的名称:
<input type="hidden" name="owner" value="phil" id="id_owner" />
当提交表单并返回到我的 views.py 时,我尝试这样处理它:
form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
但是,我得到的是类型转换错误,因为它无法将字符串“phil”(保存到“owner”字段中的用户名)转换为 Int 以将其转换为 ForeignKey。
那么这里发生了什么。 ModelForm 是否应该将外键表示为数字并透明地处理它?还是我需要自己将 id 提取到表单的所有者字段中?如果是这样,在我尝试验证表单之前,我如何以及何时将其映射回来?
最佳答案
我怀疑 Profile 模型实例的 __unicode__
方法或其 repr
被设置为返回 self.id
以外的值>。例如,我刚刚设置了这个:
# models.py
class Profile(models.Model):
name = models.CharField('profile name', max_length=10)
def __unicode__(self):
return u'%d' % self.id
class Plan(models.Model):
name = models.CharField('plan name', max_length=10)
profile = models.ForeignKey(Profile, related_name='profiles')
def __unicode__(self):
return self.name
# forms.py
class PlanForm(forms.ModelForm):
profile = forms.ModelChoiceField(queryset=Profile.objects.all(),
widget=forms.HiddenInput())
class Meta:
model = Plan
# views.py
def add_plan(request):
if request.method == 'POST':
return HttpResponse(request.POST['profile'])
profile = Profile.objects.all()[0]
form = PlanForm(initial={'profile':profile})
return render_to_response('add_plan.html',
{
'form':form,
},
context_instance=RequestContext(request))
有了它,我在模板中看到 PlanForm.profile 是这样呈现的:
<input type="hidden" name="profile" value="1" id="id_profile" />
关于python - Django 表格 : Foreign Key in Hidden Field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/621212/