如何用管理员内联中的实际对象字段替换

如何用管理员内联中的实际对象字段替换

本文介绍了如何用管理员内联中的实际对象字段替换 content_type 和 object_id 字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有内联,它显示 contenttype 模型的数据,所以我看到的是 content_typeobject_id 字段而不是真实对象.我可以 exclude 这些字段 - 这不是问题,但我也想在下拉列表中使用另一个 Places 获取真实对象作为 selected.谁能告诉我,我该怎么做?

I have inline, which shows data of contenttype model, so instead of real objects, I see content_type and object_id fields. I can exclude these fields - this is not a problem, but also I want to get real object as selected with another Places in a dropdown list. Could anyone tell me, how can I do this?

型号:

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,类似于:

I can add to CriteriaPlacesInlineAdmin a form, something like:

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

但我怎样才能将 object_id 传递到此表单查询,以便在下拉列表中获得选定"位置?

but how can I passadd object_id to this formquery in order to get 'selected' place in the dropdown list?

推荐答案

找到解决方案.

将表单添加到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

这篇关于如何用管理员内联中的实际对象字段替换 content_type 和 object_id 字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:48