开始学习DRF

main
RogerWork 1 year ago
parent 0f0a525915
commit 247f0f6722
  1. 35
      apps/goods/serializers.py
  2. 13
      apps/goods/urls.py
  3. 170
      apps/goods/views.py
  4. 163
      apps/goods/views2.py
  5. 32
      apps/goods/views_api.py
  6. BIN
      requirements.txt
  7. 4
      templates/goods/goods_add.html
  8. 6
      templates/goods/goods_index.html

@ -0,0 +1,35 @@
from rest_framework import serializers
from apps.goods.models import *
class GoodsCateSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField()
class GoodsSerializers(serializers.Serializer):
name = serializers.CharField(required=True, max_length=100)
# category = serializers.CharField(required=False)
category = GoodsCateSerializer(required=False, read_only=True)
market_price = serializers.DecimalField(max_digits=8, decimal_places=2)
price = serializers.DecimalField(max_digits=8, decimal_places=2)
def create(self, validated_data):
print(type(validated_data), validated_data)
return Goods.objects.create(**validated_data)
def update(self, instance, validated_data):
print(type(validated_data), validated_data)
instance.name = validated_data.get('name')
instance.market_price = validated_data.get('market_price')
instance.price = validated_data.get('price')
instance.save()
return instance
class GoodsModelSerializer(serializers.ModelSerializer):
category = GoodsCateSerializer(required=False, read_only=True)
class Meta:
model = Goods
fields = '__all__'

@ -17,10 +17,15 @@ Including another URLconf
from django.contrib import admin
from django.urls import path
from apps.goods import views
from apps.goods import views_api
urlpatterns = [
path('cate_index/', views.GoodCateView.as_view(), name='cate_index'),
path('cate_add/', views.GoodCateAddView.as_view(), name='cate_add'),
path('index/', views.GoodView.as_view(), name='good_index'),
path('add/', views.GoodsAddView.as_view(), name='good_add')
# path('cate_index/', views.GoodCateView.as_view(), name='cate_index'),
# path('cate_add/', views.GoodCateAddView.as_view(), name='cate_add'),
# path('index/', views.GoodView.as_view(), name='good_index'),
# path('add/', views.GoodsAddView.as_view(), name='good_add'),
# path('index/goods/ajax_goods/', views.ajax_goods, name='ajax_goods')
path('goods_api/', views.GoodsView.as_view()),
path('goods_model_api/', views.GoodsModelView.as_view()),
path('goods_api_d/', views_api.goods_list),
]

@ -1,152 +1,22 @@
from django.shortcuts import render, redirect, reverse
from django.http.response import JsonResponse
from django.views.generic.base import View
from rest_framework.views import APIView
from rest_framework.response import Response
from apps.goods.models import *
from apps.goods.forms import *
# Create your views here.
class GoodCateView(View):
def get(self, request):
cates = GoodsCategory.objects.all()
return render(request, 'goods/cate_index.html', {'cates': cates})
def post(self, request):
pass
class GoodCateAddView(View):
def __init__(self):
self.alist = []
def bind_data(self, data, _id, n):
if id == 0:
data = data.filter(parent__isnull=True)
else:
data = data.filter(parent=_id)
for d in data:
print(d)
self.alist[d.id] = self.space_length(n) + d.name
self.bind_data(d, d.id, n + 2)
return self.alist
def space_length(self, i):
space = ''
for j in range(1, i):
space += "  "
return space + "|--"
def get(self, request):
form_obj = GoodsCateForm()
return render(request, 'goods/cate_add.html', {'form_obj': form_obj})
def post(self, request):
form_obj = GoodsCateForm(request.POST, request.FILES)
if form_obj.is_valid():
name = request.POST.get('name', '')
cates = GoodsCategory.objects.filter(name=name)
if cates:
info = '分类已经存在'
else:
cate = GoodsCategory.objects.create(**form_obj.cleaned_data)
return redirect('cate_index')
return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': info})
else:
errors = form_obj.errors
print(errors)
return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': errors})
class GoodView(View):
def __init__(self):
self.alist = {}
def bind_data(self, data, _id, n):
data = GoodsCategory.objects.filter(parent_id=_id)
for d in data:
self.alist[data.id] = self.spacelength(n) + d.name
self.bind_data(data, d.id, n + 2)
return self.alist
def spacelength(self, i):
space = ''
for j in range(1, i):
space += "  "
return space + "|--"
def get(self, request):
cates_all = GoodsCategory.objects.all()
cates = self.bind_data(cates_all, 0, 1)
return render(request, 'goods/goods_index.html', {'cates': cates})
def post(self, request):
pass
class GoodsAddView(View):
def __init__(self):
self.alist = {}
def binddata(self, datas, id, n):
if id == 0:
datas = GoodsCategory.objects.filter(parent__isnull=True)
else:
datas = GoodsCategory.objects.filter(parent_id=id)
for data in datas:
self.alist[data.id] = self.spacelength(n) + data.name
self.binddata(datas, data.id, n + 2)
return self.alist
def spacelength(self, i):
space = ''
for j in range(1, i):
space += "  "
return space + "|--"
def get(self, request):
cates_all = GoodsCategory.objects.all()
cates = self.binddata(cates_all, 0, 1)
return render(request, 'goods/goods_add.html', {'cates': cates})
def post(self, request):
name = request.POST.get('name', '')
parent_id = request.POST.get('parent_id', '')
market_price = request.POST.get('market_price', '0')
price = request.POST.get('price', '0')
goods_desc = request.POST.get('goods_desc', '')
main_img = request.POST.get('main_img', '')
message = '字段需要填写'
if not name:
message = '请输入姓名'
return redirect(reverse('index'))
def ajax_goods(request):
cate_id = request.POST.get('cate_id', '')
goodname = request.POST.get('goodname', '')
status = request.POST.get('status')
search_dict = dict()
if cate_id:
search_dict['category'] = cate_id
if goodname:
search_dict['name__contains'] = goodname
if status:
search_dict['status'] = status
page_size = 2
page = int(request.GET['page'])
total = Goods.objects.filter(**search_dict).count()
goods = Goods.objects.filter(**search_dict).order_by('-id')[(page - 1) * page_size: page * page_size]
rows = []
datas = {'total': total, 'row': rows}
for good in goods:
rows.append({
'id': good.id,
'name': good.name,
'market_price': good.market_price,
'price': good.price,
'category_id': good.category.name,
'click_num': good.click_num,
'amount': good.amount,
})
return JsonResponse(datas, safe=False, json_dumps_params={'ensure_ascii': False, 'indent': 4})
from apps.goods.serializers import *
class GoodsView(APIView):
def get(self, request, *args, **kwargs):
goods = Goods.objects.all()[:10]
goods_json = GoodsSerializers(goods, many=True)
print(goods_json)
print(goods_json.data)
return Response(goods_json.data)
class GoodsModelView(APIView):
def get(self, request, *args, **kwargs):
goods = Goods.objects.all()[:10]
goods_json = GoodsModelSerializer(goods, many=True)
print(goods_json)
print(goods_json.data)
return Response(goods_json.data)

@ -0,0 +1,163 @@
from django.shortcuts import render, redirect, reverse
from django.http.response import JsonResponse
from django.views.generic.base import View
from apps.goods.models import *
from apps.goods.forms import *
# Create your views here.
class GoodCateView(View):
def get(self, request):
cates = GoodsCategory.objects.all()
print(cates)
return render(request, 'goods/cate_index.html', {'cates': cates})
def post(self, request):
pass
class GoodCateAddView(View):
def __init__(self):
self.alist = []
def bind_data(self, data, _id, n):
if id == 0:
data = data.filter(parent__isnull=True)
else:
data = data.filter(parent=_id)
for d in data:
print(d)
self.alist[d.id] = self.space_length(n) + d.name
self.bind_data(d, d.id, n + 2)
return self.alist
def space_length(self, i):
space = ''
for j in range(1, i):
space += "  "
return space + "|--"
def get(self, request):
form_obj = GoodsCateForm()
return render(request, 'goods/cate_add.html', {'form_obj': form_obj})
def post(self, request):
form_obj = GoodsCateForm(request.POST, request.FILES)
if form_obj.is_valid():
name = request.POST.get('name', '')
cates = GoodsCategory.objects.filter(name=name)
if cates:
info = '分类已经存在'
else:
cate = GoodsCategory.objects.create(**form_obj.cleaned_data)
return redirect('cate_index')
return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': info})
else:
errors = form_obj.errors
print(errors)
return render(request, 'goods/cate_add.html', {'form_obj': form_obj, 'info': errors})
class GoodView(View):
def __init__(self):
self.alist = {}
def binddata(self, datas, id, n):
if id == 0:
datas = GoodsCategory.objects.filter(parent__isnull=True)
else:
datas = GoodsCategory.objects.filter(parent_id=id)
for data in datas:
self.alist[data.id] = self.spacelength(n) + data.name
self.binddata(datas, data.id, n + 2)
return self.alist
def spacelength(self, i):
space = ''
for j in range(1, i):
space += "  "
return space + "|--"
def get(self, request):
cates_all = GoodsCategory.objects.all()
cates = self.binddata(cates_all, 0, 1)
print(cates)
return render(request, 'goods/goods_index.html', {'cates': cates})
def post(self, request):
pass
class GoodsAddView(View):
def __init__(self):
self.alist = {}
def binddata(self, datas, id, n):
if id == 0:
datas = GoodsCategory.objects.filter(parent__isnull=True)
else:
datas = GoodsCategory.objects.filter(parent_id=id)
for data in datas:
self.alist[data.id] = self.spacelength(n) + data.name
self.binddata(datas, data.id, n + 2)
return self.alist
def spacelength(self, i):
space = ''
for j in range(1, i):
space += "  "
return space + "|--"
def get(self, request):
cates_all = GoodsCategory.objects.all()
cates = self.binddata(cates_all, 0, 1)
return render(request, 'goods/goods_add.html', {'cates': cates})
def post(self, request):
good_dict = dict()
good_dict['name'] = request.POST.get('name', '')
cate_id = request.POST.get('parent_id', '')
if cate_id:
good_dict['category'] = GoodsCategory.objects.filter(id=cate_id)
good_dict['market_price'] = request.POST.get('market_price', '0')
good_dict['price'] = request.POST.get('price', '0')
good_dict['goods_desc'] = request.POST.get('goods_desc', '')
good_dict['main_img'] = request.POST.get('main_img', '')
message = '字段需要填写'
if not good_dict['name']:
message = '请输入姓名'
r = Goods.objects.create(**good_dict)
print(r)
return redirect(reverse('good_index'))
def ajax_goods(request):
cate_id = request.POST.get('cate_id', '')
goodname = request.POST.get('goodname', '')
status = request.POST.get('status')
search_dict = dict()
if cate_id:
search_dict['category'] = cate_id
if goodname:
search_dict['name__contains'] = goodname
if status:
search_dict['status'] = status
page_size = 2
page = int(request.GET['page'])
total = Goods.objects.filter(**search_dict).count()
goods = Goods.objects.filter(**search_dict).order_by('-id')[(page - 1) * page_size: page * page_size]
rows = []
datas = {'total': total, 'row': rows}
for good in goods:
print(good.category.name)
rows.append({
'id': good.id,
'name': good.name,
'market_price': good.market_price,
'price': good.price,
'category_id': good.category.name,
'click_num': good.click_num,
'amount': good.amount,
})
return JsonResponse(datas, safe=False, json_dumps_params={'ensure_ascii': False, 'indent': 4})

@ -0,0 +1,32 @@
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from apps.goods.models import *
from apps.goods.serializers import *
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def goods_list(request, *args, **kwargs):
if request.method == 'GET':
# 获取数据
print(args)
print(kwargs)
print(request.query_params)
if _id := request.query_params.get('id'):
goods = Goods.objects.filter(id=_id)
else:
goods = Goods.objects.all()[:10]
# 序列化
goods_json = GoodsSerializers(goods, many=True)
print(goods_json.data)
return Response(goods_json.data)
elif request.method == 'POST':
data = request.data
print(data)
serializer_data = GoodsSerializers(data=data, many=False)
if serializer_data.is_valid():
goods = serializer_data.save()
return Response(serializer_data.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer_data.errors, status=status.HTTP_400_BAD_REQUEST)

Binary file not shown.

@ -34,7 +34,7 @@
<div class="card-body">
<div class="form-group">
<label for="id_name">商品名称</label>
<input type="text" class="form-control" placeholder="请输入商品名称" minlength="2"
<input type="text" class="form-control" name="name" placeholder="请输入商品名称" minlength="2"
required id="id_name">
</div>
<div class="form-group">
@ -56,7 +56,7 @@
<input type="text" name="price" class="form-control" placeholder="请输入销售价" required
onkeyup="value=value.replace(/[^\d.]/g, '')">
</div>
<div class="form-control">
<div class="form-group">
<label for="id_pic_main">商品主图片</label>
<div class="custom-file">
{{ form_obj.logo }}

@ -29,7 +29,7 @@
<ul>
<li>
<label>分类:</label>
<select id="cate_id">
<label for="cate_id"></label><select id="cate_id">
<option selected value="">请选择...</option>
{% for key,value in cates.items %}
<option value="{{ key }}">{{ value|safe }}</option>
@ -89,8 +89,8 @@
var temp = {
page: (params.offset / params.limit) + 1,
cate_id: $('#cate_id').val(),
goodname: $(#goodname).val(),
status: $('status').val()
goodname: $('#goodname').val(),
status: $('#status').val()
};
return temp;
},

Loading…
Cancel
Save