Reputation: 107
in app/models.py:
class Template(models.Model):
user = models.ForeignKey(User);
in app/admin.py:
class TemplateAdmin(admin.ModelAdmin):
list_display = ('user', 'status',);
When I edit Template table in Site Adminitration, I get a dropdown for user field. The value in the dropdown is 'username', but app_templates stores the user value as 'user_id'.
How do I make such that the dropdown in Site Adminitration will show combination of first_name, last_name, email instead of 'username'? But, 'templates' table will store the value as 'id'?
Thank you!
Upvotes: 1
Views: 2146
Reputation: 107
Change 'user' to:
list_display = ('full_username')
Add the following to class Template:
def full_username(self):
return str(self.user.first_name) + ' ' + str(self.user.last_name) + ' ' + str(self.user.email);
Upvotes: 0
Reputation: 7450
From Django Docs:
The unicode (str on Python 3) method of the model will be called to generate string representations of the objects for use in the field’s choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it.
https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield
So to override it:
class UserChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return '%s - %s - %s' % (obj.first_name, obj.last_name, obj.email)
class TemplateAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TemplateAdminForm, self).__init__(*args, **kwargs)
self.fields['user'] = UserChoiceField(queryset=User.objects.all())
class TemplateAdmin(admin.ModelAdmin):
form = TemplateAdminForm
Upvotes: 1