Daryl
Daryl

Reputation: 1489

Override Django User model __unicode__

Currently, Django 1.2.3 User model unicode is

def __unicode__(self):
    return self.username

and I'd like to override it so its:

def __unicode__(self):
    return u'%s, %s' % (self.last_name, self.first_name)

How to?

To similar effect:

User._meta.ordering = ['last_name', 'first_name']

works when defined anywhere

Upvotes: 17

Views: 7467

Answers (5)

Zorig
Zorig

Reputation: 605

I just found this simple method on django 1.5

def __unicode__(self):
   a = self.last_name
   b = self.first_name 
   c = a+ "-" +b
   return c 

it will return what you want

Upvotes: 0

user2564293
user2564293

Reputation: 131

Django's Proxy Model solved this problem.

This is my solution:

form.fields['students'].queryset = Student.objects.filter(id__in = school.students.all())

Here school.students is a m2m(User), Student is a proxy model of User.

class Student(User):
    class Meta:
        proxy = True
    def __unicode__(self):
        return 'what ever you want to return'

All above helps you to solve if your want to show your User ForeignKey in your custom method. If your just want to change it in admin view, there is a simple solution:

def my_unicode(self):
    return 'what ever you want to return'

User.__unicode__ = my_unicode

admin.site.unregister(User)
admin.site.register(User)

add these codes to admin.py, it works.

Upvotes: 5

Franz
Franz

Reputation: 744

If you simply want to show the full name in the admin interface (which is what I needed), you can easily monkey-patch it during runtime. Just do something like this in your admin.py:

from django.contrib import admin
from django.contrib.auth.models import User

def user_unicode(self):
    return  u'%s, %s' % (self.last_name, self.first_name)

User.__unicode__ = user_unicode

admin.site.unregister(User)
admin.site.register(User)

Upvotes: 36

GabiMe
GabiMe

Reputation: 18483

If you need to override these, chances are you would need more customizations later on. The cleanest practice would be using a user profile models instead of touching the User model

Upvotes: 0

mtgred
mtgred

Reputation: 1449

Create a proxy User class.

class UserProxy(User):
    class Meta:
        proxy = True
        ordering = ['last_name', 'first_name']

    def __unicode__(self):
        return u'%s, %s' % (self.last_name, self.first_name)

Upvotes: 0

Related Questions