开发者

Override default User model method

开发者 https://www.devze.com 2022-12-13 06:43 出处:网络
I\'ve been trying to override the default __unicode__() method for the django.contrib.auth.models User model but I can\'t get it to work.

I've been trying to override the default __unicode__() method for the django.contrib.auth.models User model but I can't get it to work.

I tried it like this:

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

class User(models.Model):
        def __unicode__(self):
            return "pie"

and

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

class User(User):
        def __unicode__(self):
            return "pie"

but it's not working, I know it's wrong like that but I have no idea how to do it properly.

All I want it to do is to say "pie" instead of the user name inside the admin panel.

edit:

Managed to do it like this:

class MyUser(User):
    class Meta:
        proxy = True

    de开发者_开发问答f __unicode__(self):
        if self.get_full_name() == '':
            return "pie"
        else:
            return self.get_full_name()

I used the MyUser class when making ForeignKey references, instead of User.


You might want to look at Django's Proxy Model concept. They even show an example using User as a base class.

On the other hand, if you are trying to change the actual __unicode__() method in the actual User class, you probably will have to MonkeyPatch it. It's not difficult, but I'll leave the specifics as a learning experience for you.

0

精彩评论

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