inline中的实际对象替换字段的content

inline中的实际对象替换字段的content

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

问题描述

我有内联代码,它显示 contenttype 模型的数据,所以我看到的是 content_type 而不是真实对象。 object_id 字段。我可以排除这些字段-这不是问题,但是我也想通过选择 获得真实对象下拉列表中的地方。谁能告诉我,我该怎么办?

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)

Admin:

class CriteriaPlacesInlineAdmin(admin.TabularInline):
    model = PlacesToCriterias

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

admin.site.register(Criterias, CriteriasAdmin)

我可以添加到 CriteriaPlacesInlineAdmin 一张表单,例如:

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 pass\add object_id to this form\query 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

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

08-21 07:44