另一个Django表单:隐藏字段中的外键 [英] Another Django Forms : Foreign Key in Hidden Field

查看:162
本文介绍了另一个Django表单:隐藏字段中的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个Django表单问题。

Another Django Form question.

我的表单:

class PlanForm(forms.ModelForm):    
    owner = forms.ModelChoiceField(label="",
                                  queryset=Profile.objects.all(),
                                  widget=forms.HiddenInput())
    etc...

    class Meta:
        model = Plan

模型中的所有者是个人档案的ForeignKey。

Owner, in the model, is a ForeignKey to a 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(保存在所有者字段中的用户名称)转换为Int将其转换为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆