'用户'对象没有属性'用户名'

ree*_*evh 3 django django-models tastypie

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

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()
Run Code Online (Sandbox Code Playgroud)

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

'用户'对象没有属性'用户名'

编辑用户模型:

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'))
Run Code Online (Sandbox Code Playgroud)

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

def add_to_cart(self, request, **kwargs):
    self.method_check(request, allowed=['post'])
    self.is_authenticated(request)
Run Code Online (Sandbox Code Playgroud)

追溯:

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'
Run Code Online (Sandbox Code Playgroud)

Mik*_*maa 6

当Django打包依赖于类似Django 1.4的模型时,你最有可能的用户对象总是有一个username字段.问题出在您自己的代码或第三方代码中,但问题没有足够的细节可讲.

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

  • 如果修补程序包可用,请更新它们

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

关于Django 1.5+用户模型:

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

您最有可能是用户id识别用户,而不是username