Bootstrap

django2 rest api

版本django 2.2.3,我用的社区版

1.安装django:pycharm——Settings——Project Interpreter——选择你要的Python解释器版本——点击右侧的加号,输入django,点安装。

验证是否安装成功:python -m django --version

2.同样的方法安装djangorestframework,markdown,django-filter

3.进入要存放项目的目录,输入django-admin startproject django1

4.打开settings,在INSTALLED_APPS下添加

'rest_framework',

5.打开urls.py,在urlpatterns下添加

url(r'^api-auth/', include('rest_framework.urls'))
可能需要在上方添加
from django.conf.urls import url,include

6.在settings中添加

REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }

7.在有manage.py的目录下,执行指令,该指令用于创建数据库,默认使用sqlite:python manage.py migrate

8.在有manage.py的目录下,执行指令,创建管理员:python manage.py createsuperuser

9.将urls.py改成以下这个样子:

from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'is_staff']

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

10.运行程序 运行manage.py 参数是runserver

转载于:https://www.cnblogs.com/MarsMercury/p/11191499.html

;