Python Django:在自定义ModelForm中,是否可以从content\u对象模型字段压缩具有值的表单字段?
My models.py的外观如下(部分): 内容对象可以指向任何模型。我想将这种模型的值压缩到一个表单字段中。 我的表格是这样的:Python Django:在自定义ModelForm中,是否可以从content\u对象模型字段压缩具有值的表单字段?,python,django,Python,Django,My models.py的外观如下(部分): 内容对象可以指向任何模型。我想将这种模型的值压缩到一个表单字段中。 我的表格是这样的: class GalleryAdminForm(ModelForm): content_object = TextInput() def __init__(self, *args, **kwargs): """ """ super(GalleryAdminForm, self).__init__(
class GalleryAdminForm(ModelForm):
content_object = TextInput()
def __init__(self, *args, **kwargs):
"""
"""
super(GalleryAdminForm, self).__init__(*args, **kwargs)
class Meta:
model = GalleryItem
有可能吗。我应该在哪里上车?请看一下
根据此说明,您的gallery/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)
嗯。我想出来了。但我认为这是一种肮脏的做法:
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
您想要下拉列表中所有可能是FK的对象,还是下拉列表中所有类型的对象?只需要几个特定的模型(在我的例子中是Image()、Video()、Sound()。我不想要所有的内容类型。实际上我已经尝试过了,因为GalleryItems fk,通用内联中的GalleryItems指向Gallery。就好像它想把画廊添加到另一个画廊。下拉列表中只有“多媒体资料”。
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