开发者

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_开发者_StackOverflowname, self.first_name)

How to?

To similar effect:

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

works when defined anywhere


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)


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.


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


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜