-1

I am using a custom form in admin panel with two autocomplete fields among the others.

My problem is that I don't know how to use the form in update action in order the stored data to appear with the autocomplete functionality.

In my implementation in update action the values appearing without autocomplete functionality.

How can I fix that?

my form

class ModelSeoMetadatumForm(forms.ModelForm):
    name = ModelChoiceField(
        required=False, 
        queryset=MetaTag.objects.exclude(name__isnull=True).values_list('name', flat=True).distinct(), 
        widget=autocomplete.ModelSelect2(url='seo:name-autocomplete')
    )

    property = ModelChoiceField(
        required=False, 
        queryset=MetaTag.objects.exclude(property__isnull=True).values_list('property', flat=True).distinct(), 
        widget=autocomplete.ModelSelect2(url='seo:property-autocomplete')
    )

    class Meta:
        model = ModelSeoMetadatum
        fields = ('name', 'content', 'property', 'content_type', 'object_id')

my admin

@admin.register(ModelSeoMetadatum)
class ModelSeoMetadatumAdmin(admin.ModelAdmin):
    add_form  = ModelSeoMetadatumForm
    list_display = ('id', 'name', 'content', 'property', 'content_object')
    fields = ('name', 'content', 'property', 'content_type', 'object_id')


    def get_form(self, request, obj=None, **kwargs):
        defaults = {}
        if obj is None:
            defaults['form'] = self.add_form
        defaults.update(kwargs)
        return super().get_form(request, obj, **defaults)
gtopal
  • 544
  • 1
  • 9
  • 35

2 Answers2

0

I've been fighting with this same problem myself for quite some time.

It didn't work until I found out that from Django 3.2 on, instead of MyModel._meta.get_field('some_lookup_field').remote_field you needed to pass to AutocompleteSelect MyModel._meta.get_field('some_lookup_field')

So without the .remote_field

So for me :

class MyForm(forms.ModelForm):
    class Meta:
        widgets = {
            'some_lookup_field': AutocompleteSelect(
                MyModel._meta.get_field('some_lookup_field'),
                admin.site,
                attrs={'style': 'width: 20em'},
            ),
        }

works just fine

Skratt
  • 289
  • 4
  • 13
-1

You should overwrite the widget and give it the admin site as parameter.

admin class:

class MyAdmin(admin.ModelAdmin):
    form = MyForm

form definition:

class MyForm(forms.ModelForm):
    class Meta:
        widgets = {
            'some_lookup_field': AutocompleteSelect(
                MyModel._meta.get_field('some_lookup_field').remote_field,
                admin.site,
                attrs={'style': 'width: 20em'},
            ),
        }

Note, you need to have at lease one search_filter in the admin definition of your lookup field.

Have a look here for an improved version that expands if needed link

Jan Staal
  • 31
  • 1
  • 6