Django Rest Framework Token Authentication

前端 未结 7 1262
北荒
北荒 2020-12-07 08:24

I have read the Django Rest Framework Guides and done all the tutorials. Everything seemed to make sense and work just how it should. I got basic and session authentication

相关标签:
7条回答
  • 2020-12-07 09:10

    Just to add my two cents to this, if you've got a custom user manager that handles user creation (and activation), you may also perform this task like so:

    from rest_framework.authtoken.models import Token
    # Other imports
    
    class UserManager(BaseUserManager):
    
        def create_user(self, **kwargs):
            """
            This is your custom method for creating user instances. 
            IMHO, if you're going to do this, you might as well use a signal.
    
            """
            # user = self.model(**kwargs) ...
            Token.objects.create(user=user)
    
        #You may also choose to handle this upon user activation. 
        #Again, a signal works as well here.
    
        def activate_user(**kwargs):
            # user = ...
            Token.objects.create(user=user)
    

    If you already have users created, then you may drop down into the python shell in your terminal and create Tokens for all the users in your db.

    >>> from django.contrib.auth.models import User
    >>> from rest_framework.authtoken.models import Token 
    >>> for user in User.objects.all():
    >>> ...    Token.objects.create(user=user)
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题