简体   繁体   中英

Display field for User ForeignKey in Django admin

class Lab(Model):
  responsible = ForeignKey(User)

This is a very simplified version of my Django model. Basically the problem is in the Django admin, when I want to edit or add a new Lab object, the drop-down list containing the User objects only displays the User.username value, which are only numbers in my case.

I want the drop-down list to display User.last_name value.

How can I do this?

You have to define your own user choice field for lab admin.

from django import forms
from django.contrib import admin


class UserChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.last_name

# Now you have to hook this field up to lab admin.

class LabAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'responsible':
            kwargs['form_class'] = UserChoiceField
        return super(LabAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

Something like that. I didn't tested it so there may be some typos. Hope this helps!

Default User model in django returns username as the object representation. If you want to change this, then you have to overwrite __unicode__ method.

You cant write a proxy model to extend the user model and then overwrite the __unicode__ method to return last_name

Something like this:

class MyUser(User):
   class Meta:
      proxy = True

   def __unicode__(self):
        return self.last_name


class Lab(Model):
   responsible = ForeignKey(MyUser)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM