简体   繁体   English

django-autocomplete-light的管理表单

[英]Admin form for django-autocomplete-light

I am trying to use the django-autocomplete-light to add some nice autocomplete features to a Django Admin form. 我正在尝试使用django-autocomplete-light向Django Admin表单添加一些不错的自动完成功能。 (DAL certainly seems to be the best/most popular and seems to have a lot of great features, it is a shame the docs are so poorly structured). (DAL当然似乎是最受欢迎/最受欢迎的,并且似乎具有很多很棒的功能,但是文档结构如此差很可惜)。

The autocomplete field does not get created if I create an admin form like this: 如果我创建这样的管理表单,则不会创建自动完成字段:

@admin.register(RaffleTicket)
class RaffleTicketAdmin(admin.ModelAdmin):
    model = RaffleTicket
    code = forms.IntegerField()
    bought_by = autocomplete_light.ModelChoiceField('PersonAutocomplete')

But it works if I create a plain ModelForm (which I never use anywhere else) and shove it directly into my ModelAdmin , like so: 但是,如果我创建一个普通的ModelForm (在其他地方从未使用过)并将其直接推到ModelAdmin ,则可以使用它,如下所示:

class RaffleTicketForm(forms.ModelForm):
    code = forms.IntegerField()
    bought_by = autocomplete_light.ModelChoiceField('PersonAutocomplete')


@admin.register(RaffleTicket)
class RaffleTicketAdmin(admin.ModelAdmin):
    model = RaffleTicket
    form = RaffleTicketForm

Why is it so? 为什么会这样呢? And is there a better way (ie single class definition) to do this than what I have found? 还有比我发现的更好的方法(即单个类定义)吗?

The first code doesn't work because it sets form fields in the modeladmin class, which has no reason to work at all, you haven't seen that in any documentation, ever. 第一个代码不起作用,因为它在modeladmin类中设置了表单字段,根本没有理由使用它,您从未在任何文档中看到它。

Did you try just this ? 您尝试过这个吗?

@admin.register(RaffleTicket)
class RaffleTicketAdmin(admin.ModelAdmin):
    model = RaffleTicket
    form = autocomplete_light.modelform_factory(RaffleTicket)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM