Django表单:隐藏字段中的外键 [英] Django Forms: Foreign Key in Hidden Field
问题描述
我的表单
class PlanForm(forms.ModelForm):
owner = forms.ModelChoiceField(label="",
queryset=Profile.objects.all(),
widget=forms.HiddenInput())
etc...
class Meta:
model = Plan
模型中的所有者是配置文件的外键。
Owner, in the model, is a ForeignKey to a Profile.
设置此表单时,将所有者的值设置为Profile对象。
When I set this form, I set the value of "owner" to be a Profile object.
出现在表单上,似乎包含配置文件的名称,如下所示:
But when this comes out on the form, it seems to contain the name of the Profile like this:
<input type="hidden" name="owner" value="phil" id="id_owner" />
提交表单并返回到我的views.py时,我尝试按以下方式处理:
When the form is submitted and gets back to my views.py I try to handle it like this:
form = PlanForm(request.POST)
...
if form.is_valid():
plan = form.save()
return HttpResponseRedirect('/plans/%s'%plan.id) # Redirect after POST
但是,我得到的是一个类型转换错误,因为它无法将字符串 phil(保存到所有者字段中的用户名)转换为将其转换为ForeignKey。
However, what I get is a type-conversion error as it fails to turn the string "phil" (the user's name that was saved into the "owner" field) into an Int to turn it into the ForeignKey.
那么,这是怎么回事。 ModelForm是否应该将外键表示为数字并透明地处理它?还是我需要将ID本身提取到表单的所有者字段中?如果是这样,在尝试验证表单之前,如何以及何时将其映射回?
So what is going on here. Should a ModelForm represent a foreign key as a number and transparently handle it? Or do I need to extract the id myself into the owner field of the form? And if so, how and when do I map it back BEFORE I try to validate the form?
推荐答案
我怀疑Profile模型实例的 __ unicode __
方法,或其中的 repr
设置为返回 self.id
以外的值。例如,我只是将其设置为:
I suspect that the __unicode__
method for the Profile model instance, or the repr
thereof is set to return a value other than self.id
. For example, I just set this up:
# 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:
With that, I see PlanForm.profile rendered thus in the template:
<input type="hidden" name="profile" value="1" id="id_profile" />
这篇关于Django表单:隐藏字段中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!