1-DRF - 常见报错
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
django3.2 + python3.9 + djangorestframework3.14.0
前提是如果你创建的Django项目,使用其全部功能,即没有注释掉任何settings.py中的各种组件和中间件,就不会遇到这个报错。
我从别处找了个页面报错截图:
这个报错在使用drf框架时,如果你用的是纯净版的Django,也就是不启用Django内置的auth、admin这些组件,那么我们在settings配置文件中,就会做如下配置:
DEBUG = True
ALLOWED_HOSTS = ["*"]
# 注释掉相关的apps
INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
'django.contrib.staticfiles',
'api.apps.ApiConfig',
'rest_framework'
]
# 注释掉相应的中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 模板中也注释掉相应的配置
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',
],
},
},
]
然后总路由urls.py中也删除默认的admin:
# from django.contrib import admin
from django.urls import path
urlpatterns = [
# path('admin/', admin.site.urls),
]
完事执行完默认的数据库迁移之后,写个视图类:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from api import models
from utils.encrypt import get_md5
class LoginSerializer(serializers.Serializer):
""" 登录序列化器,因为登录不涉及保存数据库,所以直接用 serializers.Serializer 进行字段校验即可"""
mobile = serializers.CharField(required=True)
password = serializers.CharField(required=True)
def validated_password(self, value):
return get_md5(value)
class LoginView(APIView):
""" 登录视图类 """
def post(self, request):
print(request.data)
ser = LoginSerializer(data=request.data)
if not ser.is_valid():
return Response(ser.errors)
return Response(ser.data)
然后你去访问它,你会发现报错:
这是因为drf的APIView内部会走认证源码,相关代码导致的报错,怎么解决呢?就是在settings.py中配置上如下两个参数即可:
REST_FRAMEWORK = {
"UNAUTHENTICATED_USER": None,
"UNAUTHENTICATED_TOKEN": None,
}
然后,重启项目,就可以了。