Search code examples
pythondjangomodelextend

Django extending user model tutorial isn't work for me


I've use this tutorial and do exactly what they do: https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model

my model.py:

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

class Chess(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    last_activity = models.DateTimeField(default=datetime(1970,1,1,))
    is_avaliable  = models.BooleanField(default=False,)
    in_progress  = models.BooleanField(default=False,)

my admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User

from chess_tournament.models import Chess

class ChessInline(admin.StackedInline):
    model = Chess
    can_delete = False
    verbose_name_plural = 'Chess'

# Define a new User admin
class UserAdmin(BaseUserAdmin):
    inlines = (ChessInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

in managaer.py shell:

from django.contrib.auth.models import User
u = User.objects.get(pk=1)
u.username # return 'admin' it's work
u.chess.last_activity # return ERROR (described below)

AttrinbuteError: 'User' object has no attribute 'chess'

  • but in django admin panel this field are available and works

Please help to figure it out coz I already spent 4 hours for it...


Solution

  • You need to update your Chess model and add related_name to the user property.

    class Chess(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="chess_board")
        # Other Stuff
    

    Now you can easily access last_activity or any other property:

    u.chess_board.last_activity
    

    Hope it helps.