Django - 自动完成 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。我唯一的问题是在管理员的事件跟踪模型中使用它。

所以,实际上很容易:

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
    ...

相关内容

  • 没有找到相关文章

最新更新