当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: