I have created a model that keeps track of employees and a basic text field for an HR record. I would like to access this model in the Django admin but the dropdown menu lists usernames instead of full names which is nearly impossible to navigate. I would like the Django admin user dropdown menu to display a list of users by Last Name, First Name and ordered by last name. I would like to do this in the admin.py and/or models.py instead of creating a separate forms.py file.
My model is listed below …
class EmployeeHR(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, blank=True, null=True)
record = models.TextField(blank=True)
def __str__(self):
return self.user
```
Thanks for your help in advance....
Hi @mbellazzini, can you also provide how you have configured your model-admins?
Keep in mind that a ForeignKey dropdown uses the __str__ method and default ordering for the referenced model.
Hoever my suggestion, to provide a better experience, is to use automcomplete_fields or raw_id_fields which scales up way better than the default (when the database grows large the default dropdown widget for foreign key is unusable, since it fetches the whole referenced table).
Thank you for your prompt reply. Admin code is below. I am not familiar with use of autocomplete or raw id. Can you provide an example of how this would allow me to see Last Name, First Name order by last name in the drop down list? Thanks.
Ok, I made some progress by modifying users/models.py returning the f string with last and first name but the ordering still does not work. The drop down is displaying last_name, first name and not username anymore. Any suggestions to order by last name?
class CustomUser(AbstractUser):
objects = CustomUserManager()
class Meta:
ordering = ['last_name']
def __str__(self):
return f"{self.last_name.title()}, {self.first_name.title()}" or self.get_username()
Well after continued searching the problem is solved….
To get the Django Admin User dropdown to display last_name, first_name instead of username modify the users/models.py file ….
class CustomUser(AbstractUser):
objects = CustomUserManager()
def __str__(self):
return f"{self.last_name.title()}, {self.first_name.title()}" or self.get_username()
To get the Django Admin User dropdown to display a sorted list edit your your_app/admin.py file. This is my admin file so you will need to change the model names…