user2429940
user2429940

Reputation:

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?

Upvotes: 2

Views: 1410

Answers (2)

Ander2
Ander2

Reputation: 5658

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)

Upvotes: 2

iperelivskiy
iperelivskiy

Reputation: 3581

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!

Upvotes: 5

Related Questions