drf+vue基本使用

创建项目

参考https://blog.csdn.net/qq_43357874/article/details/108194004
drf+vue基本使用_第1张图片

修改settings.py

INSTALLED_APPS = [
   	... 
    'tutorial.quickstart',
 
]

新建models.py

from django.db import models


# Create your models here.
class Older(models.Model):
    card = models.BigIntegerField()
    gender = models.CharField(max_length=10)
    date = models.CharField(max_length=50)
    age = models.IntegerField()
    phone = models.CharField(max_length=30)
    disable = models.CharField(max_length=10)
    name = models.CharField(max_length=20)

新建序列化器,serializers.py

from rest_framework import serializers
from tutorial.quickstart.models import Older


class OlderSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Older
        fields = ('card', 'name', 'gender', 'date', 'age', 'phone', 'disable')

新建视图, views.py

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from tutorial.quickstart.serializers import OlderSerializer

@api_view(['GET', 'POST'])
def older_list(request):
    if request.method == 'GET':
        global Older
        Older = Older.objects.all()
        serializer = OlderSerializer(Older, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = OlderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

修改urls.py

from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views

# 使用自动URL路由连接我们的API。
# 另外,我们还包括支持浏览器浏览API的登录URL。
urlpatterns = [
    url(r'^older/$', views.older_list),
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

测试

drf+vue基本使用_第2张图片

使用浏览器

测试get
drf+vue基本使用_第3张图片

使用postman

测试post
drf+vue基本使用_第4张图片

vue 使用

跨域问题CORS

参考https://www.cnblogs.com/xujunkai/p/12266205.html

# 后端下载模块:
pip install django-cors-headers

# settings配置:
INSTALLED_APPS = [
    ...
    'corsheaders',
]
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
  	...
]
CORS_ORIGIN_ALLOW_ALL = True

测试commit

drf+vue基本使用_第5张图片

在这里插入图片描述

你可能感兴趣的:(DRF)