How do I login to the Django Rest browsable API wh

2019-07-26 03:56发布

I have a custom user model as follows in account/models.py

from django.contrib.auth.modles import AbstractUser
from django.db.models.signals import post_save
from rest_framework.authtoken.models import Token
from django.db import models
from django.dispatch import receiver
from django.conf import settings

@receiver(post_save, sender=settings.AUTH_USER_MODEL)                                
def create_auth_token(sender, instance=None, created=False, **kwargs):               
    if created:                                                                      
        Token.objects.create(user=instance)                                          

class UserProfile(AbstractUser):                                                     
    gender = models.CharField(max_length=1,default='') 

and in settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

...

AUTH_USER_MODEL = "account.UserProfile"

However, whenever I try to log into the browsable API, it asks me to use a correct username and password, and I am using credentials of users who are both marked as superusers and staff.

The manage.py runserver console shows this status message:

[27/Jul/2016 20:41:39] "POST /api-auth/login/ HTTP/1.1" 200 2897

1条回答
爷、活的狠高调
2楼-- · 2019-07-26 04:32

I've ran into this before too and from what I remember it's because the built-in DRF auth form is not using TokenAuthentication, but rather SessionAuthentication. Try adding rest_framework.authentication.SessionAuthentication to your DEFAULT_AUTHENTICATION_CLASSES tuple

查看更多
登录 后发表回答