T
T
TitanFighter2016-10-14 17:52:08
Django
TitanFighter, 2016-10-14 17:52:08

How to replace the content_type and object_id fields in inline in the admin panel with a drop-down list with the selected object?

I have an inline that renders the contenttype of the model, thus rendering the content_type and object_id fields. I can hide them using exclude, but I also need to display a dropdown list with all "Places" and the selected current location based on the content_type and object_id. How can I do it?
Models:

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)

I can add a form to the inline CriteriaPlacesInlineAdmin:
class CriteriaPlacesChoicesFieldForm(forms.ModelForm):
    places = forms.ModelChoiceField(PlaceTypesGroups.objects.all(), label='place')

but how in this case to pass content_type and object_id to this form to get a dropdown list with all "Places" and with current place selected based on content_type and object_id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TitanFighter, 2016-10-14
@TitanFighter

Solution found.
Add form to `admin.TabularInline`:

class CriteriaPlacesInlineAdmin(admin.TabularInline):
    model = PlacesToCriterias
    form = CriteriaPlacesChoicesFieldForm  # <- ADDED FORM
    
class CriteriasAdmin(admin.ModelAdmin):
    inlines = [CriteriaPlacesInlineAdmin]
    
admin.site.register(Criterias, CriteriasAdmin)

The form itself:
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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question