如何在Django管理页面中添加多个自动完成功能

时间:2018-09-24 00:10:49

标签: python django django-models

我正在使用内置功能为许多领域建立自动完成功能: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields

我有以下模型:

 class Ipaddress(models.Model):
        ipaddress=models.CharField(max_length=20)
        slug = models.SlugField(unique=True)
        machinename=models.CharField(max_length=500)
        user=models.CharField(max_length=200)
        department= models.ForeignKey('Department',on_delete=models.CASCADE,default='Empty')
        location= models.ForeignKey('Location', on_delete=models.CASCADE)
        updated = models.DateField("Date Updated",null=True)
        note =models.TextField()

    def __str__(self):
        return self.ipaddress[:50]

class Department(models.Model):
    name= models.CharField(max_length=100, unique=True)
    def __str__(self):
        return self.name[:50] 

class Location(models.Model):
    description= models.CharField(max_length=100, unique=True)
    def __str__(self):
        return self.description[:50] 

管理页面在这里:

from django.contrib import admin
from pages.models import  Ipaddress, DeviceGroup, Location,Department,
from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter

class IpaddressAdmin(admin.ModelAdmin):
        prepopulated_fields = {'slug': ('ipaddress',)}

        search_fields = ['ipaddress']
        autocomplete_fields = ['department',]

        list_display = ('ipaddress', 'machinename', 'user', 'department','location','updated',)
        list_filter = (
        ('user', DropdownFilter),
        ('department', RelatedDropdownFilter),
        ('location', RelatedDropdownFilter),

    )

如果我更改了autocomplete_fields = ['location',],它会起作用,但是当我尝试更改其部门时,它将不起作用。我也想同时具有部门和位置的自动完成功能。

我看到的错误是我设置autocomplete_fields = ['department',]

ERRORS:<class 'pages.admin.IpaddressAdmin'>: (admin.E040) ModelAdmin must define    
"search_fields", because it's referenced by 
IpaddressAdmin.autocomplete_fields.

任何想法如何解决此错误 我想要这样的事情:

 autocomplete_fields = ['department', 'location','user',]

1 个答案:

答案 0 :(得分:5)

根据您在链接here

中引用的文档
  

您必须在相关对象的ModelAdmin上定义search_fields,因为自动完成搜索会使用它。

在您的情况下以及从出现的错误中,这意味着您需要在相关对象上定义 search_fields (在您的情况下 {{ 1}} Location Department类,因为自动完成搜索会使用它。)

所以,就像这样。

ModelAdmin

您在class DepartmentAdmin(admin.ModelAdmin): search_fields = ['name'] class LocationAdmin(admin.ModelAdmin): search_fields = ['description'] 上的autocomplete_fields可能像这样。

IPAddressAdmin