yourlabs / django-autocomplete-light

A fresh approach to autocomplete implementations, specially for Django. Status: v4 alpha, v3 stable, v2 & v1 deprecated.
https://django-autocomplete-light.readthedocs.io
MIT License
1.81k stars 468 forks source link

Can't add auto-complete on OneToOne Field using views #1011

Open simemon opened 6 years ago

simemon commented 6 years ago

I am not able to add auto-complete for the OneToOneField in Django admin using django-autocomplete-light. This field is available in Django Rest Framework's auth_token model.

class Token(models.Model):
    """
    The default authorization token model.
    """
    key = models.CharField(_("Key"), max_length=40, primary_key=True)
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, related_name='auth_token',
        on_delete=models.CASCADE, verbose_name=_("User")
    )
    created = models.DateTimeField(_("Created"), auto_now_add=True)

models.py

from rest_framework.authtoken.models import Token

class CustomAuthTokenModel(Token):
    search_fields = ['user', ]

    def __str__(self):
        return str(self.user)

views.py

from dal import autocomplete
from rest_framework.authtoken.models import Token

class AuthUserAutocompleteView(autocomplete.Select2QuerySetView):
    def get_queryset(self):

        qs = Token.objects.all().order_by('user__username')

        if self.q:
            qs = qs.filter(user__username__icontains=self.q)

        return qs

admin.py

from django.contrib import admin

from rest_framework.authtoken.models import Token
from rest_framework.authtoken.admin import TokenAdmin
from .forms import AuthUserForm

class CustomTokenAdmin(TokenAdmin):
    form = AuthUserForm

admin.site.unregister(Token)
admin.site.register(Token, CustomTokenAdmin)

forms.py

from dal import autocomplete
from .models import CustomAuthTokenModel

class AuthUserForm(autocomplete.FutureModelForm):
    class Meta:
        model = CustomAuthTokenModel
        fields = ('user', )
        search_fields = ['user__username']
        widgets = {
            'user': autocomplete.ModelSelect2(url='autocomplete_auth_user')
        }

urls.py has

url('^autocomplete_auth_user/$', AuthUserAutocompleteView.as_view(), name='autocomplete_auth_user')

Is there a issue from my side, there is an issue in dal. Tried a few other things, did not resolve the issue. How would you add auto-complete when you do not model is being exactly used. Currently it shows me the entry in terms of keys.

jpic commented 6 years ago

can you reproduce this in a test_project app ? you can fork the repo and add your own app