django-rest-framework+vxe-table实现前后端分离式开发表格交互-完整增删改查功能

1. 效果图:

django-rest-framework+vxe-table实现前后端分离式开发表格交互-完整增删改查功能_第1张图片

后端依赖:

Django==3.1.5
django-cors-headers==3.6.0
django-filter==2.4.0
djangorestframework==3.12.2

2. models.py代码

from django.db import models


class PersonInfo(models.Model):
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    nickname = models.CharField(max_length=255, null=True, blank=True)
    role = models.CharField(max_length=255)
    sex = models.CharField(max_length=255, null=True, blank=True, choices=((1, "男"), (0, "女")))
    age = models.CharField(max_length=255, null=True, blank=True)
    age2 = models.CharField(max_length=255, null=True, blank=True)
    amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    language = models.CharField(max_length=255, null=True, blank=True)
    birthday = models.CharField(max_length=255, null=True, blank=True)
    color = models.CharField(max_length=255, null=True, blank=True)
    level = models.CharField(max_length=255, null=True, blank=True)
    level2 = models.CharField(max_length=255, null=True, blank=True)
    describe = models.CharField(max_length=255, null=True, blank=True)
    flag = models.CharField(max_length=255, null=True, blank=True)
    flag1 = models.CharField(max_length=255, null=True, blank=True)
    flag2 = models.CharField(max_length=255, null=True, blank=True)
    flag3 = models.CharField(max_length=255, null=True, blank=True)
    num = models.CharField(max_length=255, null=True, blank=True)
    num1 = models.CharField(max_length=255, null=True, blank=True)
    num2 = models.CharField(max_length=255, null=True, blank=True)
    num3 = models.CharField(max_length=255, null=True, blank=True)
    num4 = models.CharField(max_length=255, null=True, blank=True)
    date = models.DateField(null=True, blank=True)
    date1 = models.DateField(null=True, blank=True)
    date2 = models.DateField(null=True, blank=True)
    date3 = models.DateField(null=True, blank=True)
    date4 = models.DateField(null=True, blank=True)
    attr1 = models.CharField(max_length=255, null=True, blank=True)
    attr2 = models.CharField(max_length=255, null=True, blank=True)
    attr3 = models.CharField(max_length=255, null=True, blank=True)
    attr4 = models.CharField(max_length=255, null=True, blank=True)
    attr5 = models.CharField(max_length=255, null=True, blank=True)
    attr6 = models.CharField(max_length=255, null=True, blank=True)
    attr7 = models.CharField(max_length=255, null=True, blank=True)
    attr8 = models.CharField(max_length=255, null=True, blank=True)
    attr9 = models.CharField(max_length=255, null=True, blank=True)
    attr10 = models.CharField(max_length=255, null=True, blank=True)
    attr11 = models.CharField(max_length=255, null=True, blank=True)
    attr12 = models.CharField(max_length=255, null=True, blank=True)
    attr13 = models.CharField(max_length=255, null=True, blank=True)
    attr14 = models.CharField(max_length=255, null=True, blank=True)
    attr15 = models.CharField(max_length=255, null=True, blank=True)
    createDate = models.DateTimeField(auto_now_add=True)
    updateDate = models.DateTimeField(auto_now=True)
    createBy = models.CharField(max_length=255, default="", null=True, blank=True)
    updateBy = models.CharField(max_length=255, default="", null=True, blank=True)

3. serializers.py代码

from rest_framework import serializers
from app01.models import PersonInfo
from datetime import datetime


class PersonInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = PersonInfo
        fields = "__all__"

4. filters.py代码

import django_filters
from django_filters.rest_framework import FilterSet
from .models import PersonInfo


class PersonInfoFilter(FilterSet):
    role = django_filters.CharFilter(field_name='role')
    name = django_filters.CharFilter(field_name='name')
    email = django_filters.CharFilter(field_name='email')
    sex = django_filters.CharFilter(field_name='sex')
    age = django_filters.CharFilter(field_name='age')
    nickname = django_filters.CharFilter(field_name='nickname')

    class Meta:
        model = PersonInfo
        fields = ("role", 'name', 'email', 'sex', 'age')

5.  views.py代码

from app01.models import PersonInfo
from app01.serializers import PersonInfoSerializer
from django_filters.rest_framework import DjangoFilterBackend
from .filters import PersonInfoFilter
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework import filters
from rest_framework import generics
import json


class GPersonInfoList(generics.ListCreateAPIView):
    queryset = PersonInfo.objects.all().order_by("id")
    serializer_class = PersonInfoSerializer

    # 分页配置
    pagination_class = PageNumberPagination
    # 过滤、搜索、排序配置
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filter_class = PersonInfoFilter
    # search_fields = ["id", "name", "email", "nickname", "role", "amount"]
    ordering_fields = ["name", "role", "age", "updateDate", "createDate"]

    def get(self, request, *args, **kwargs):
        # 动态配置每页显示的条数
        self.pagination_class.page_size = args[0]
        return self.list(request, *args, **kwargs)


class PersonInfoSave(APIView):
    def post(self, request):
        body = request.body.decode("utf8")
        dict_body = json.loads(body)

        # 即新增又修改
        if dict_body.get("insertRecords") and dict_body.get("updateRecords"):
            self.insert_person(dict_body)
            return self.update_person(dict_body)
        elif dict_body.get("insertRecords"):
            # 新增记录
            print(dict_body)
            return self.insert_person(dict_body)
        elif dict_body.get("updateRecords"):
            # 修改记录
            return self.update_person(dict_body)

        if dict_body["removeRecords"]:
            # 删除记录
            return self.remove_person(dict_body)

    @staticmethod
    def insert_person(dict_body):
        # 新增记录
        dict_data = dict_body["insertRecords"]
        print(dict_data)
        for data in dict_data:
            personinfo = PersonInfoSerializer(data=data, partial=True)
            if personinfo.is_valid():
                personinfo.save()
            else:
                for key, value in personinfo.errors.items():
                    print(key, ":", value)
                return Response(status=status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_200_OK)

    @staticmethod
    def update_person(dict_body):
        dict_data = dict_body["updateRecords"]
        for data in dict_data:
            id = data["id"]
            obj = PersonInfo.objects.get(id=id)
            p = PersonInfoSerializer(instance=obj, data=data)
            if p.is_valid():
                p.save()
            else:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_200_OK)

    @staticmethod
    def remove_person(dict_body):
        # 删除记录
        remove_dict = dict_body["removeRecords"]
        for remove_d in remove_dict:
            remove_obj = PersonInfo.objects.get(id=remove_d["id"])
            remove_obj.delete()
        return Response(status=status.HTTP_200_OK)


class GPersonInfoAll(generics.ListAPIView):
    """导出或打印所有数据时会调用此接口"""
    queryset = PersonInfo.objects.all()
    serializer_class = PersonInfoSerializer


class SexList(APIView):
    def get(self, request):
        data = [{'label': '男', 'value': 1}, {'label': '女', 'value': 0}]
        return Response(data=data, status=status.HTTP_200_OK)

6. urls.py代码

from django.urls import path, re_path
from app01 import views

urlpatterns = [
    re_path("personinfo/list/(\d+)/", views.GPersonInfoList.as_view(), name="person_info_list"),
    path("personinfo/all/", views.GPersonInfoAll.as_view(), name="person_info_all"),
    path("personinfo/save/", views.PersonInfoSave.as_view(), name="person_info_save"),
    path("personinfo/sexlist/", views.SexList.as_view(), name="sexlist"),
]

7. App.vue代码




8. main.js代码

import Vue from 'vue'
import App from './App'
// import router from './router'
import axios from 'axios'
import qs from 'qs'
import VueResource from 'vue-resource'
import XEUtils from 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import XEAjax from 'xe-ajax'

// 全局注册
Vue.config.productionTip = false
Vue.prototype.$axios = axios
Vue.prototype.$qs = qs
Vue.prototype.$XEAjax = XEAjax
Vue.prototype.$XEUtils = XEUtils
Vue.use(VueResource)
Vue.use(VXETable)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  // router,
  components: { App },
  template: ''
})

 

你可能感兴趣的:(django+vue前后端分离)