我的models.py看起来像那样(部分):
class GalleryItem(models.Model):
gallery = models.ForeignKey(Gallery)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return str(self.object_id)
content_object可以指向任何模型。我想将这种模型的值压缩到一个表单字段中。 我的表格看起来像这样:
class GalleryAdminForm(ModelForm):
content_object = TextInput()
def __init__(self, *args, **kwargs):
"""
"""
super(GalleryAdminForm, self).__init__(*args, **kwargs)
class Meta:
model = GalleryItem
有可能吗?我应该在哪里上钩?
答案 0 :(得分:1)
确定。我想到了。但我认为这是一种肮脏的方式:
class GalleryAdminForm(ModelForm):
content_object = CharField()
def __init__(self, *args, **kwargs):
super(GalleryAdminForm, self).__init__(*args, **kwargs)
related = self.instance.content_object
if related:
self.initial['content_object'] = related.title+related.file.__unicode__()
class Meta:
model = GalleryItem