我使用本教程并完成他们的工作: https://docs.djangoproject.com/ja/1.9/topics/auth/customizing/#extending-the-existing-user-model
我的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,)
我的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)
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'对象没有属性'chess'
请帮助弄清楚因为我已经花了4个小时才能...
答案 0 :(得分:0)
你有可能没有注册国际象棋模型吗?
尝试在admin.py底部添加admin.site.register(Chess, ChessAdmin)
。当然,您可能必须先创建一个简单的ChessAdmin才能显示。
答案 1 :(得分:0)
您需要更新Chess
模型并将related_name
添加到user
媒体资源。
class Chess(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="chess_board")
# Other Stuff
现在您可以轻松访问last_activity
或任何其他财产:
u.chess_board.last_activity
希望它有所帮助。