thodoris
thodoris

Reputation: 69

django-autocomplete-light foreign key form

I have followed the tutorial for django-autocomplete-light http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html but i have the following question.

I have a model

class Order(models.Model):
    client = models.ForeignKey(Client)
    product = ....

If i create a form as described in the tutorial

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('__all__')
        widgets = {
            'client': autocomplete.ModelSelect2(url='ordersapp:client-autocomplete')
    }

and in admin.py

class OrderAdmin(admin.ModelAdmin):
    form = OrderForm

I get the desired result, which is autocomplete for the clients filed.

But if i don't want to create a form and use instead

class OrderAdmin(admin.ModelAdmin):
    .....

is there a way to have the autocomplete widget for the client field? I appreciate any help.

Upvotes: 1

Views: 820

Answers (1)

thodoris
thodoris

Reputation: 69

I overrode finally get_form like this and it worked

def get_form(self, request, obj=None, **kwargs):
    form = super(OrderAdmin, self).get_form(request, obj, **kwargs)
    form.base_fields['client'].widget = autocomplete.ModelSelect2(url='ordersapp:client-autocomplete')
    return form

Upvotes: 1

Related Questions