Max*_*cia 4 python django rest login
我有一个自定义用户模型,如下所示 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='')
Run Code Online (Sandbox Code Playgroud)
并在 settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
Run Code Online (Sandbox Code Playgroud)
...
AUTH_USER_MODEL = "account.UserProfile"
Run Code Online (Sandbox Code Playgroud)
但是,每当我尝试登录可浏览的 API 时,它都会要求我使用正确的用户名和密码,并且我使用的是标记为超级用户和员工的用户凭据。
该manage.py runserver控制台显示这条消息:
[27/Jul/2016 20:41:39] "POST /api-auth/login/ HTTP/1.1" 200 2897
Run Code Online (Sandbox Code Playgroud)
小智 7
Django Rest Framework“登录可浏览的 API”使用会话身份验证而不是令牌身份验证。要将登录添加到可浏览的 API,请按照以下步骤操作:
第 1 步:在项目的“urls.py”文件中添加以下内容。
from django.urls import path, include
urlpatterns += [path('api-auth/', include('rest_framework.urls')),]Run Code Online (Sandbox Code Playgroud)
步骤2:您在“DEFAULT_AUTHENTICATION_CLASSES”中仅添加了TokenAuthentication,您还需要添加sessionAuthentication。更改您的代码如下:
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
),Run Code Online (Sandbox Code Playgroud)
我以前也遇到过这个问题,我记得这是因为内置的 DRF 身份验证表单没有使用 TokenAuthentication,而是使用 SessionAuthentication。尝试添加rest_framework.authentication.SessionAuthentication到您的DEFAULT_AUTHENTICATION_CLASSES元组
| 归档时间: |
|
| 查看次数: |
3677 次 |
| 最近记录: |