I am using built in function to build autocomplete for many fields: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields
I have following model:
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]
The admin page is here:
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),
)
If i change the autocomplete_fields = ['location',]
it works but it does not work when i try to change it department. Also i want to have autocomplete for both department and location at the same time.
The error i am seeing is when i set autocomplete_fields = ['department',]
ERRORS:<class 'pages.admin.IpaddressAdmin'>: (admin.E040) ModelAdmin must define
"search_fields", because it's referenced by
IpaddressAdmin.autocomplete_fields.
Any idea how to fix this error I want to some thing like this:
autocomplete_fields = ['department', 'location','user',]
As per the documentation that you have referenced in your link here
You must define search_fields on the related object’s
ModelAdmin
because the autocomplete search uses it.
What this means, in your case and also from the error that you are getting is you need to define your search_fields
on the related object ( in your case Department
and Location ModelAdmin
classes, because the autocomplete search uses it).
So, it would be something like this.
class DepartmentAdmin(admin.ModelAdmin):
search_fields = ['name']
class LocationAdmin(admin.ModelAdmin):
search_fields = ['description']
Your autocomplete_fields
on your IPAddressAdmin
can then be like this.
autocomplete_fields = ['department', 'location',]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With