How to override default display values for a select field for foreign keys in the Django Admin?

django, django-admin

Solution

You need to create custom `Form` for this and set form attribute in your `ModelAdmin`.

In that `Form` you will need to override form field type of `user` field on model to custom `ModelChoiceField`.

`ModelChoiceField` has a method called `label_from_instance`, you need to override that to get full name.

Example code

######################################
## models.py ##
######################################

from django.db import models
from django.contrib.auth.models import User

class Item(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField("name", max_length=60)

    def __unicode__(self):
        return self.name

######################################
## forms.py ##
######################################

from django import forms
from django.contrib.auth.models import User

from .models import Item


class CustomUserChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
         return obj.get_full_name()


class ItemForm(forms.ModelForm):
    user = CustomUserChoiceField(queryset=User.objects.all())

    class Meta:
        model = Item

######################################
## admin.py ##
######################################

from django.contrib import admin

from .models import Item
from .forms import ItemForm


class ItemAdmin(admin.ModelAdmin):
    form = ItemForm


admin.site.register(Item, ItemAdmin)

Source Code Reference

https://github.com/django/django/blob/1.4.5/django/forms/models.py#L948

Related Questions

- Django admin - change ForeignKey display text

- Django forms: how to dynamically create ModelChoiceField labels

- Change Django ModelChoiceField to show users' full names rather than usernames

- Django show get_full_name() instead or username in model form

- django: customizing display of ModelMultipleChoiceField

- django how to display users full name in FilteredSelectMultiple

- Django ModelChoiceField drop down box custom population

- customize select in django admin

- Use method other than unicode in ModelChoiceField Django

Problem

I'm creating models, where each model should be related with a user, like this: ``` class Item(models.Model): user = models.ForeignKey(User) ``` But then in the Django Admin, for an `Item`, it shows a `select` field with all the users listed by their usernames. In addition to their usernames, I also need to display each user's `first_name` and `last_name`. How can all three fields be displayed together within that select list in the Django Admin interface?

Original source

Related problems