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,
}