我尝试按照以下示例进行操作https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model关于如何扩展用户模型。但我无法检索附加到用户的模型数据。
model
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
ip = models.IntegerField(default=0)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
获取我的 User 对象
user = auth.authenticate(username=username, password=password)
g = user.UserProfile.ip
print(g)
用户被正确获取,并且我能够获取标准用户的所有数据。但 user.UserProfile 会导致:
Internal Server Error: /Crowd/login/
Traceback (most recent call last):
File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 35, in login
g = user.UserProfile.ip
AttributeError: 'User' object has no attribute 'UserProfile'
[05/Sep/2016 04:32:46] "POST /Crowd/login/ HTTP/1.1" 500 69185
我检查了我的数据库,可以看到 UserProfile 中有一行与 User 有关系。所以 UserProfile 已正确创建(我假设)。