Login

Show users' full names for foreign keys in admin

Author:
SmileyChris
Posted:
July 19, 2009
Language:
Python
Version:
1.0
Score:
5 (after 5 ratings)

This is a ModelAdmin base class you can use to make foreign key references to User a bit nicer in admin. In addition to showing a user's username, it also shows their full name too (if they have one and it differs from the username).

2009-08-14: updated to handle many to many fields and easily configure whether to always show the username (if it differs from full name)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.contrib import admin
from django.contrib.auth.models import User


class NiceUserModelAdmin(admin.ModelAdmin):
    """
    In addition to showing a user's username in related fields, show their full
    name too (if they have one and it differs from the username).
    """
    always_show_username = True

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(NiceUserModelAdmin, self).formfield_for_foreignkey(
                                                db_field, request, **kwargs)
        if db_field.rel.to == User:
            field.label_from_instance = self.get_user_label
        return field

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        field = super(NiceUserModelAdmin, self).formfield_for_manytomany(
                                                db_field, request, **kwargs)
        if db_field.rel.to == User:
            field.label_from_instance = self.get_user_label
        return field

    def get_user_label(self, user):
        name = user.get_full_name()
        username = user.username
        if not self.always_show_username:
            return name or username
        return (name and name != username and '%s (%s)' % (name, username)
                or username)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

davidrhoden (on November 4, 2021):

How would you use this in an admin template? I want to use a field in list_filter but showing the user's full name instead of username.

#

Please login first before commenting.