如何用admin inline中的实际对象替换content_type和object_id字段?

时间:2016-10-13 20:40:04

标签: django django-admin

我有内联,它显示contenttype模型的数据,因此我会看到content_typeobject_id字段而不是真实对象。我可以exclude这些字段 - 这不是问题,但我也希望在下拉列表中将另一个selected作为Places的真实对象。谁能告诉我,我怎么能这样做?

型号:

class Criterias(models.Model):
    name = ...

class Places(models.Model):
    name = ...

class PlacesToCriterias(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

    criteria_group = models.ForeignKey(Criterias)

管理:

class CriteriaPlacesInlineAdmin(admin.TabularInline):
    model = PlacesToCriterias

class CriteriasAdmin(admin.ModelAdmin):
    inlines = [CriteriaPlacesInlineAdmin]

admin.site.register(Criterias, CriteriasAdmin)

我可以添加CriteriaPlacesInlineAdmin一个form,例如:

class CriteriaPlacesChoicesFieldForm(forms.ModelForm):
    places = forms.ModelChoiceField(PlaceTypesGroups.objects.all(), label='place')

但是如何通过\添加object_id添加到此表单\查询以便选择'放在下拉列表中?

1 个答案:

答案 0 :(得分:1)

找到解决方案。

将表单添加到admin.TabularInline

class CriteriaPlacesInlineAdmin(admin.TabularInline):
    model = PlacesToCriterias
    form = CriteriaPlacesChoicesFieldForm  # <- ADDED FORM

class CriteriasAdmin(admin.ModelAdmin):
    inlines = [CriteriaPlacesInlineAdmin]

admin.site.register(Criterias, CriteriasAdmin)

形式:

class CriteriaPlacesChoicesFieldForm(forms.ModelForm):
    ct_place_type = ContentType.objects.get_for_model(PlaceTypesGroups)

    object_id = forms.ModelChoiceField(PlaceTypesGroups.objects.all(), label='places')
    content_type = forms.ModelChoiceField(ContentType.objects.all(), initial=ct_place_type, widget=forms.HiddenInput())

    def clean_object_id(self):
        return self.cleaned_data['object_id'].pk

    def clean_content_type(self):
        return self.ct_place_type