创建drf纯净项目
1)创建项目
django-admin startproject api
2)创建app
django-admin startproject api_app
3)修改settings.py注释掉一些没用的配置
INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
]
ROOT_URLCONF = 'api.urls'
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',
],
},
},
]
4)安装drf
pip3 install djangorestframework
5)注册drf
setttings.py
INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', #注册drf
]
3.3创建url路由和CBV
urlpatterns = [
# path('admin/', admin.site.urls),
path('home/', views.home),
path('user/', views.UserView.as_view()), #CBV路由
]
class UserView(APIView):
def get(self,request):
return Response('返回成功')
这时候访问user/会报错,因为没有用户信息
Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
需要在settings.py加入以下代码:
#将未认证用户置空
REST_FRAMEWORK = {
"UNAUTHENTICATED_USER":None,
}
原文地址:https://blog.csdn.net/weixin_43631940/article/details/142626465
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!