django-autocomplete-light django 1.8 custom modelform for admin

608 views Asked by At

I want add autocomplete for OneToOne field to django-admin

class Banner(models.Model):
    product = models.OneToOneField(Product, null=True)

class BannerAdmin(admin.ModelAdmin):
    form = BannerForm

stucked on https://django-autocomplete-light.readthedocs.org/en/stable-2.x.x/tutorial.html?highlight=tutorial#tutorial - anything changed after all following steps (same list widget for 'product' ...):

What I have done:

  1. installed :D
  2. added 'autocomplete_light', to INSTALLED_APPS
  3. overrided admin/base_site.html (using custom loader)
  4. url(r'^autocomplete/', include('autocomplete_light.urls')), to urlpatterns
  5. autocomplete_light_registry.py with model Banner and search_fields=['product'],
  6. updated modelform:
class BannerForm(autocomplete_light.ModelForm):
    class Meta:
        model = Banner
        fields = ['product', 'priority', 'image']
        autocomplete_fields = ['product']

What I've missed?

1

There are 1 answers

0
madzohan On BEST ANSWER

Following resolved my problem:

  1. before admin in INSTALLED_APPS
  INSTALLED_APPS = (
    'autocomplete_light',
    'django.contrib.admin',
  )
  1. autocomplete_light_registry.py
class BannerAutocomplete(autocomplete_light.AutocompleteModelBase):
    model = Banner
    search_fields = ('name',)  # banner_obj.product.name
    choices = Product.objects.all()
    limit_choices = 20

    autocomplete_light.register(
        BannerAutocomplete,
        attrs={
            'placeholder': _(u'имя товара'),
            'data-autocomplete-minimum-characters': 1,
        },
    )
  1. Manually select autocomplete for related field in your form:
class BannerForm(autocomplete_light.ModelForm):
    class Meta:
        model = Banner
        fields = ['product', 'priority', 'image']
        autocomplete_names = {'product': 'BannerAutocomplete'}