Reputation: 4606
I need to use user_id instead id in my custom user model(don't ask why, it's a long story :)). I try to use code from django example, but when it I tried to log in into admin backend, I got In template site-packages/django/contrib/admin/templates/admin/index.html, error at line 60 'User' object has no attribute 'id'
Line with error looks like
{% get_admin_log 10 as admin_log for_user user %}
#UserManager
class UserManager(BaseUserManager):
def create_user(self, login_name, email, first_name, last_name, password=None):
if not email:
raise ValueError('The given email must be set')
email = UserManager.normalize_email(email)
user = self.model(login_name=login_name, email=email,
first_name=first_name,
last_name=last_name,
is_staff=False, is_active=True, is_superuser=True)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, login_name, email, first_name, last_name, password):
u = self.create_user(login_name, email, first_name, last_name, password)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
return u
#Model
class User(AbstractBaseUser, PermissionsMixin):
user_id = models.AutoField(primary_key=True)
login_name = models.CharField(max_length=30, unique=True, db_index=True)
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
objects = UserManager()
USERNAME_FIELD = 'login_name'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
is_staff = models.BooleanField('staff status', default=False)
is_active = models.BooleanField('active', default=True)
def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
return self.first_name
#Admin
from django.contrib import admin
from applications.users.models import User
class UserAdmin(admin.ModelAdmin):
list_display = ('login_name', 'email', 'first_name', 'last_name')
admin.site.register(User, UserAdmin)
How can I fix it?
Upvotes: 2
Views: 415
Reputation: 16071
I had this problem too. Looks like this was a bug in Django. Thanks to @karthikr for pointing me towards the source (use the source luke!), but it looks like Django 1.5's admin has a hard-coded use of the "id" field, which of course may not exist if you've customised your user model.
Here's the commit in which they fix it:
https://github.com/django/django/commit/054ce2aa02c88221ffa5665a4b9a5739cbbd0a39
Looks like the fix is only available in version 1.6 though, so I guess the solution is to upgrade!
Upvotes: 2
Reputation: 29794
Quick and dirty solution:
Try this hack, it might work:
class User(AbstractBaseUser, PermissionsMixin):
...
def __getattr__(self, name):
if name='id':
return self.user_id
return self.__dict__[name]
Hope this helps!
Upvotes: 1