Django AutoComplete Light不能与OneToOne Field一起使用

时间:2018-04-30 23:03:33

标签: python django django-models django-views django-autocomplete-light

我正在尝试使用django-autocomplete-light在Django管理员中为 OneToOneField 添加自动完成功能。该字段在Django Rest Framework的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文件中,我有:

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

我很确定,我必须遗漏一些东西,因为在管理员面板中为auth令牌输入表单时我看不到用户名。让我知道我错过了什么。我正在使用Django 1.11和django-autocomplete light 3.2.10。

0 个答案:

没有答案