Login

Show users' full names for foreign keys in admin

Author:
SmileyChris
Posted:
July 19, 2009
Language:
Python
Version:
1.0
Tags:
user modeladmin get_full_name
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. Field value as plain text which can't be edited by user by szczavv 5 years, 6 months ago
  2. User manager by diverman 5 years, 8 months ago
  3. Active User Sorted ModelAdmin by daemondazz 5 years, 8 months ago
  4. Limit ForeignKey filter values to those that have a relationship with current model by overclocked 4 years, 4 months ago
  5. Use email addresses for user name by chris 8 years ago

Comments

Please login first before commenting.