【发布时间】:2012-12-15 02:20:24
【问题描述】:
我正在尝试扩展 django 中的默认用户模型。
我已经定义了一个名为 Profile 的类。
# code in myapp/models/profile.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
field = models.CharField(max_length=30)
class Meta:
app_label="myapp"
在我的视图函数中,我调用了一个出现异常的方法:
def my_view_function(request):
field = get_field(request.user)
...
def get_field(user):
return user.profile.field
# also tried return user.get_profile().field with AUTH_PROFILE_MODULE in settings.py set to "myapp.Profile", still does not work.
我的堆栈跟踪中出现 AttributeError 'unicode' object has no attribute 'get_profile'
或'unicode' object has no attribute 'profile'。
当我尝试将 get_field() 中的用户对象与字符串连接时,我收到错误消息 'str' cannot concatenate with 'SimpleLazyObject'。
我尝试阅读 request.user returns a SimpleLazyObject, how do I "wake" it? 但这没有帮助。
我正在使用中间件来确保用户已登录,因此我确定用户已登录。用户对象有什么问题?为什么 django 说用户对象有 '__unicode__' 类型。
提前致谢!
【问题讨论】:
-
您能告诉我们您在实际调用
get_field函数时使用的代码吗?你可能错误地传递了一些东西。另外,您使用的是哪个版本的 Django? (不知道的可以用pip freeze来判断。) -
我在调用 get_field 函数时精确地使用了 get_field(request.user)。函数的名称不同,但这无关紧要。
标签: python django django-models django-authentication