So, here's how it works. We override the ModelChoiceField (for ForeignKeys) and the ModelMultipleChoiceField (for ManyToMany Fields):
from django.forms import ModelChoiceField, ModelMultipleChoiceField
class UserModelChoiceField(ModelChoiceField):
'''
A ModelChoiceField to represent User
select boxes in the Auto Admin
'''
def label_from_instance(self, obj):
return "%s (%s)"%(obj.get_full_name(), obj.username)
class UserModelMultipleChoiceField(ModelMultipleChoiceField):
'''
Similar to UserModelChoiceField, provide a nicer-looking
list of user names for ManyToMany Relations...
'''
def label_from_instance(self, obj):
return "%s (%s)"%(obj.get_full_name(), obj.username)
Then, to customize the admin, you need to create a custome ModelForm for your Model. So, if I had a Model that looked like this:
class MyModel(models.Model):
user = models.ForeignKey(User)
You'd need to create the following ModelForm:
class MyModelAdminForm(forms.ModelForm):
user = UserModelChoiceField(User.objects.all().order_by('first_name', 'last_name', 'username'))
class Meta:
model = MyModel
Now, when you create a ModelAdmin class for the MyModel, you specify the above form:
from models import MyModel
from forms import MyModelAdminForm
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
admin.site.register(MyModel, MyModelAdmin)
At this point, the choices for User objects in the admin should contain the user's full name and their username in parenthesis.
comments powered by Disqus