Django:ModelForm保存另一个类的返回对象

时间:2010-12-06 20:27:03

标签: django django-forms

ipdb debug:

ipdb> form_class
<class 'myproject.apps.usersites.forms.IndividualSiteHomeForm'>
ipdb> form = form_class(request.POST)
ipdb> form
<myproject.apps.usersites.forms.IndividualSiteHomeForm object at 0x021A81F0>
ipdb> var = form.save( commit= False)
ipdb> var
<IndividualProfile: user1>
ipdb> request.POST
<QueryDict: {u'csrfmiddlewaretoken': [u'208ff2a5a78bd5c2ba9452b365b59b6d'], u'ho
me_content': [u'Some contents']}>

我将IndividualSiteHomeForm绑定到POST数据后保存。 为什么返回IndividualProfile对象?

供参考: 1 GT;模型

class IndividualSite(SiteBase):
individual = models.ForeignKey(IndividualProfile, unique=True, verbose_name = _("Professional"))
logo = models.ImageField(upload_to="sites/logos/",verbose_name=_("logo"))    
home_content = models.TextField(_("Home contents"), null=True, blank=False,
                                help_text = "This text will appear on your web site home. Do not use HTML here.")    

def __unicode__(self):
    return self.individual.name

2 - ;的ModelForm

class IndividualSiteHomeForm(ModelForm):
class Meta:
    model = IndividualSite
    exclude = ('individual','user','logo')

感谢您的时间。

编辑:确认var确实是IndividualProfile:

ipdb> var
<IndividualProfile: user1>
ipdb> var.home_content
*** AttributeError: 'IndividualProfile' object has no attribute 'home_content'
ipdb> var.__class__
<class 'profiles.models.IndividualProfile'>
ipdb>

1 个答案:

答案 0 :(得分:0)

我不认为它正在返回IndividualProfile的实例。我认为它正如你所期望的那样返回IndividualSite的实例,但是当你从shell中重新编写它时,它使用了IndividualSite的__unicode__方法 - 它返回ForeignKey的值,这是个人档案。