如何改变Django管理员中的默认小部件?

2024-09-28 23:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的项目中使用自动生成的Django管理器。结果如下:

Result

对于字段“Professor”,Django自动生成了一个下拉列表,但其中至少有1000个元素。因此,我想用更方便用户的方式替换列表,比如用于“仲裁”的小部件,基本上只需键入名称的第一个字母,元素显示在下面。在

如何修改管理员py或者模型.py得到结果的文件?在


Tags: 项目django用户py模型名称元素管理器
3条回答

您可以尝试将您的字段添加到管理员py公司名称:

class YourModelAdmin(admin.ModelAdmin):
    raw_id_fields=('professor', )

admin.site.register(YourModel, YourModelAdmin)

你会得到一个漂亮的搜索按钮

您正在寻找:

ModelAdmin.formfield_overrides

This provides a quick-and-dirty way to override some of the Field options for use in the admin. formfield_overrides is a dictionary mapping a field class to a dict of arguments to pass to the field at construction time.

看看这个例子:

from django.db import models
from django.contrib import admin

# Import our custom widget and our model from where they're defined
from myapp.widgets import RichTextEditorWidget
from myapp.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.TextField: {'widget': RichTextEditorWidget},
    }

你只需要选一个教授还是多个教授? 下拉列表的生成是因为您在模型中使用了professor = models.ForeignKey(Professor)。ForeignKey意味着单选,但是示例widget意味着多个选择。所以你的意图不太清楚。 通过下拉列表,您还可以通过键入第一个字母来选择选项。在

相关问题 更多 >