2012-01-24 21 views
0

我的models.py看起來像這樣(的一部分):Django:是否有可能從自定義ModelForm中的content_object模型字段中壓縮值的表單字段?

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

是否要在下拉菜單中選擇所有可能的對象,或者所有類型的對象都可以在下拉菜單中選擇? –

+0

只有幾個特定的​​模型(在我的情況下圖像(),視頻(),聲音())。我不想要所有的content_types。 – Memke

回答

0

請看看https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations-in-forms-and-adminhttps://docs.djangoproject.com/en/dev/ref/contrib/admin/#using-generic-relations-as-an-inline

根據這個您的畫廊/ admin.py中應包含:

from django.contrib import admin 
from django.contrib.contenttypes import generic 
from gallery.models import Gallery, GalleryItem 

class GalleryItemInline(generic.GenericTabularInline): 
    model = GalleryItem 

class GalleryAdmin(admin.ModelAdmin): 
    inlines = [ 
     GalleryItemInline, 
    ] 

admin.site.register(Gallery, GalleryAdmin) 
+0

其實我已經嘗試過和galleryItems在通用內聯點指向Gallery,因爲galleryitems fk。就好像它想將Gallery添加到Gallery一樣。下拉菜單中只有「圖庫」。 – Memke

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 
相關問題