Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default User model method

Tags:

python

django

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

    def __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.

like image 556
yoshi Avatar asked Jun 01 '26 14:06

yoshi


1 Answers

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.

like image 62
Peter Rowell Avatar answered Jun 03 '26 04:06

Peter Rowell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!