基于我以前的问题:add an object along with it's related objects in the same form in django admin 现在我决定在管理员中添加一些额外的字段和一个formset给我的modeladmin,是否可以像我的modeladmin一样添加一个像其他字段一样的formset?我的代码出了什么问题?
编辑: 我有这些模型:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery")
class Image(models.Model):
Image = models.ImageField(upload_to="gallery")
Gallery = models.ForeignKey(Gallery, related_name='images',blank=True)
class Agency(models.Model):
# some fields ...
Gallery=models.ForeignKey(Gallery)
正如你所看到的,每个代理商都有一个带有n个可选图像的HeadImage,现在我想在管理员中更改代理形式,以同样的形式处理所有这些模型,我的意思是具有HeadImage的fileinput和Image的formset的代理商model.I这样做是为了覆盖我的ModelAdmin表单。这是代码:
class AgencyAdminForm(forms.ModelForm):
HeadImage=forms.FileField(required=True)
ImageFormSet = inlineformset_factory(Gallery,Image, can_delete=True,extra=4)
class Meta:
model = Agent
def __init__(self, *args, **kwargs):
super(AgencyAdminForm, self).__init__(*args, **kwargs)
if kwargs.has_key('instance'):
instance = kwargs['instance']
self.initial['HeadImage'] = instance.HeadImage
self.initial['ImageFormSet'] = ImageFormSet(request.POST, request.FILES, instance=Gallery())
def save(self, commit=True):
model = super(AgencyAdminForm, self).save(commit=False)
gallery=Gallery.objects.create(HeadImage=self.cleaned_data['HeadImage'])
formset=self.ImageFormSet(request.POST, request.FILES, instance=gallery)
image=formset.save()
model.Gallery=gallery
if commit:
model.save()
return model
class AgencyAdmin(admin.ModelAdmin):
form = AgencyAdminForm
admin.site.register(Agency,AgencyAdmin)
我的代码导致为HeadImage添加inputfile,但它没有将formset添加到admin form.my的问题是如何像其他额外字段一样处理formset。