简体   繁体   English

在 DRF 令牌身份验证中使用自定义 django model

[英]Using custom django model in DRF Token Authentication

I want to connect a custom User model with the Django Rest Framework TokenAuthentication module.我想将自定义用户 model 与 Django Rest 框架 TokenAuthentication 模块连接起来。 I have tried the followings:我尝试了以下方法:

settings.py:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'myapp.authentication.MyOwnTokenAuthentication',
     ),
}
authentication.py:

class MyOwnTokenAuthentication(TokenAuthentication):
    model = MyOwnToken
models.py:

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    birth = models.DateField()

class MyOwnToken(models.Model):

    key = models.CharField(_("Key"), max_length=40, primary_key=True)

    user = models.OneToOneField(
        User, related_name='auth_token',
        on_delete=models.CASCADE, verbose_name="User"
    )
    created = models.DateTimeField(_("Created"), auto_now_add=True)
views.py:

class UserApi(APIView):
    authentication_classes = [MyOwnTokenAuthentication]
    permission_classes = [IsAuthenticated]

    #returns all data 
    def get(self, request):
        alldata=User.objects.all()
        alldata_serialized=UserSerializer(alldata, many=True)
        return Response(alldata_serialized.data)

The token generates fine but when I call the UserApi get then it gives WrappedAttributeError: 'User' object has no attribute 'is_active'令牌生成正常,但是当我调用 UserApi get 时,它给出 WrappedAttributeError: 'User' object has no attribute 'is_active'

can anyone help??谁能帮忙??

Thanks in advance.提前致谢。

Solved:解决了:

Added 'is_active' column to the user table and set to True.将“is_active”列添加到用户表并设置为 True。

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    birth = models.DateField()
    is_active=models.BooleanField(default=True)

and removed the并删除了

permission_classes = [IsAuthenticated]

from the views.py and it works fine.从views.py,它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM