Django - 用于连接模型的管理员自动完成灯

时间:2017-06-19 09:33:21

标签: django-admin django-1.10 django-autocomplete-light

所以我有一个定义如下的连接模型:

class EventTrack(models.Model):
    dj = models.ForeignKey(DjProfile, blank=True)
    track = models.ForeignKey(Track, blank=True)
    event = models.ForeignKey(Event, blank=True)

    def __str__(self):
        return '%s - %s' % (self.event, self.track)

我可以使用django-autocomplete-light这个模型吗? 我知道如何将它与内联模型一起使用,但我不知道如何在标准字段中使用它(在这种情况下它们是fk)。

目前我有以下内容,其中不包含自动填充功能:

class EventTrackAdmin(admin.ModelAdmin):
    fields = ['event', 'dj', 'track']
    list_display = ('event', 'dj', 'track')
    search_fields = ['event', 'dj', 'track']

admin.site.register(EventTrack, EventTrackAdmin)

编辑:

我将DjForm定义如下:

class DjForm(ModelForm):
    dj = ModelChoiceField(
        queryset=DjProfile.objects.all(),
        widget=autocomplete.ModelSelect2(url='dj-autocomplete')
    )

    class Meta:
        model = DjProfile
        fields = '__all__'

查看:

@method_decorator(login_required, name='dispatch')
class DjProfileAutocomplete(autocomplete.Select2QuerySetView):
    def get_queryset(self):
        # Don't forget to filter out results depending on the visitor !
        if not self.request.user.is_authenticated():
            return DjProfile.objects.none()

        qs = DjProfile.objects.all()

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

        return qs

路由:

from frontend.views import DjProfileAutocomplete

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^dj-autocomplete/$', DjProfileAutocomplete.as_view(create_field='name'), name='dj-autocomplete'),
]

一切正常,如果我浏览端点,我会得到带有Djs结果的json。我唯一的问题是在事件跟踪模型中使用它,在admin。

1 个答案:

答案 0 :(得分:0)

sooo,实际上很简单:

forms.py

class EventTrackForm(ModelForm):
    dj = ModelChoiceField(
        queryset=DjProfile.objects.all(),
        widget=autocomplete.ModelSelect2(url='dj-autocomplete')
    )

    class Meta:
        model = EventTrack
        fields = '__all__'

admin.py

class EventTrackAdmin(admin.ModelAdmin):
    form = EventTrackForm
    ...