Show users' full names for foreign keys in admin

 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. Convert an instance to a dictionary for use in newforms by SmileyChris 6 years ago
  2. Link raw_id_fields (both ForeignKeys and ManyToManyFields) to their change pages by EmilStenstrom 2 years, 7 months ago
  3. Shortcut for smart printing user's full name or username in template by rudyryk 2 years, 10 months ago
  4. Field value as plain text which can't be edited by user by szczavv 3 years, 7 months ago
  5. Custom change_list filter based on SimpleListFilter shows only referenced (related, used) values by darklow 3 months, 3 weeks ago

Comments

seemant (on July 19, 2009):

Thanks for this SmileyChris!

#

(Forgotten your password?)