gpt4 book ai didi

django - '用户' 对象没有属性 'username'

转载 作者:行者123 更新时间:2023-12-01 09:58:29 25 4
gpt4 key购买 nike

我有我的用户模型(Django 1.5 的AbstractBaseUser),我使用电子邮件作为用户名进行身份验证,并为我的 API 使用以下 ModelResource

class CartItemResource(ModelResource):
product = fields.ForeignKey(CartItemRelatedResource, 'product', full=True)

class Meta:
queryset = CartItem.objects.all()
resource_name = 'cart_item'
excludes = ['creation_date', 'modification_date']
allowed_methods = ['post', 'get', 'delete']
authorization = CartAuthorization()
authentication = SessionAuthentication()

当向 API 发出 GET 请求时,我得到:

'User' object has no attribute 'username'

编辑用户模型:

class User(AbstractBaseUser):
objects = UserManager()
name = models.CharField(max_length=100)
email = models.EmailField(
max_length=255,
unique=True,
)
phone = models.IntegerField(max_length=10, null=True)
is_admin = models.BooleanField(default=False, blank=True)
is_driver = models.BooleanField(default=False, blank=True)
lastOrderID = models.CharField(max_length=25, null=True)

USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['name','phone']
REQUIRED_FIELDS = ['name']

def __unicode__(self):
return self.user

def set_phone(self, phone):
self.phone = phone


class CartAuthorization(Authorization):

def read_list(self, object_list, bundle):
return object_list.filter(cart__user = self.user(bundle), cart__id = bundle.request.GET.get('cart_id'))

我在同一个资源中还有另一个 POST:

def add_to_cart(self, request, **kwargs):
self.method_check(request, allowed=['post'])
self.is_authenticated(request)

回溯:

Traceback     (most recent call last):

File "C:\Python27\lib\site-packages\tastypie\resources.py", line 195, in wrapper
response = callback(request, *args, **kwargs)

File "C:\Python27\lib\site-packages\tastypie\resources.py", line 426, in dispatch_list
return self.dispatch('list', request, **kwargs)

File "C:\Python27\lib\site-packages\tastypie\resources.py", line 454, in dispatch
self.throttle_check(request)

File "C:\Python27\lib\site-packages\tastypie\resources.py", line 551, in throttle_check
identifier = self._meta.authentication.get_identifier(request)

File "C:\Python27\lib\site-packages\tastypie\authentication.py", line 283, in get_identifier
return getattr(request.user, username_field)

File "C:\Python27\lib\site-packages\django\utils\functional.py", line 205, in inner
return func(self._wrapped, *args)

AttributeError: 'User' object has no attribute 'username'

最佳答案

当 Django 打包依赖于类似 Django 1.4 的模型时,您最有可能在其中用户对象始终具有 username 字段。问题出在您自己的代码或第三方代码中,但问题没有提供足够的详细信息。

  • 使用完整的回溯来追踪这些插件

  • 如果补丁包可用则更新它们

  • 如果没有可用的补丁,您需要自己 fork 和修补第三方代码

关于 Django 1.5+ 用户模型:

https://docs.djangoproject.com/en/stable/topics/auth/customizing/#auth-custom-user

您很可能应该使用 id 来识别用户,而不是 username

关于django - '用户' 对象没有属性 'username',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20717184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com