创建菜单子应用
python manage.py startapp menu
测试
apps/menu/views
from django.http import HttpResponse
from django.views import View
class GoodsMainMenu(View):
def get(self,request):
print("get请求")
return HttpResponse("get 请求")
def post(self,request):
print("post请求")
return HttpResponse("post 请求")
muxi_shop_back/urls
path("main_menu/", GoodsMainMenu.as_view()),
setting
把csrf中间件注释了
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",
]
接近cors跨域问题
# 解决跨域的一个插件
# pip install django-cors-headers
# 允许所有域名跨域
CORS_ORIGIN_ALLOW_ALL=True
# 允许携带cookie
CORS_ALLOW_CREDENTIALS=True
获取二级菜单列表
封装统一的返回格式
utils/ResponseMessage
import json
from django.http import HttpResponse, JsonResponse
# 我们的菜单成功了状态码就是1000
# 失败了就是1001
# 其它不确定的1002
class MenuResponse():
@staticmethod
def success(data):
result = {"status":1000,"data":data}
return HttpResponse(json.dumps(result), content_type = "application/json")
@staticmethod
def failed(data):
result = {"status": 1001, "data": data}
return HttpResponse(json.dumps(result), content_type="application/json")
@staticmethod
def other(data):
result = {"status": 1002, "data": data}
return HttpResponse(json.dumps(result), content_type="application/json")
# 商品的响应全部都是2开头的
class GoodsResponse():
@staticmethod
def success(data):
result = {"status":2000,"data":data}
return HttpResponse(json.dumps(result), content_type = "application/json")
@staticmethod
def failed(data):
result = {"status": 2001, "data": data}
return HttpResponse(json.dumps(result), content_type="application/json")
@staticmethod
def other(data):
result = {"status": 2002, "data": data}
return HttpResponse(json.dumps(result), content_type="application/json")
# 购物车的响应全部都是3开头的
class CartResponse():
@staticmethod
def success(data):
result = {"status":3000,"data":data}
return JsonResponse(result,safe=False)
@staticmethod
def failed(data):
result = {"status": 3001, "data": data}
return JsonResponse(result, safe=False)
@staticmethod
def other(data):
result = {"status": 3002, "data": data}
return JsonResponse(result, safe=False)
# 用户的响应全部都是4开头的
class UserResponse():
@staticmethod
def success(data):
result = {"status":4000,"data":data}
return JsonResponse(result,safe=False)
@staticmethod
def failed(data):
result = {"status": 4001, "data": data}
return JsonResponse(result, safe=False)
@staticmethod
def other(data):
result = {"status": 4002, "data": data}
return JsonResponse(result, safe=False)
鼠标移动到不同的商品类型显示其对应的商品
goods/models
import decimal
from django.db import models
import json
from muxi_shop_back.settings import IMAGE_URL
class Goods(models.Model):
type_id = models.IntegerField(blank=True, null=True)
name = models.CharField(max_length=255, blank=True, null=True)
sku_id = models.CharField(max_length=255, blank=True, null=True)
target_url = models.CharField(max_length=255, blank=True, null=True)
jd_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
p_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
image = models.CharField(max_length=255, blank=True, null=True)
shop_name = models.CharField(max_length=255, blank=True, null=True)
shop_id = models.IntegerField(blank=True, null=True)
spu_id = models.CharField(max_length=255, blank=True, null=True)
mk_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
vender_id = models.IntegerField(blank=True, null=True)
find = models.IntegerField(blank=True, null=True)
create_time = models.DateTimeField(blank=True, null=True)
def __str__(self):
result = {}
result['type_id']=self.type_id
result['name']=self.name
result['sku_id']=self.sku_id
result['target_url']=self.target_url
result['jd_price']=self.jd_price
result['p_price']=self.p_price
result['image']= IMAGE_URL + self.image
result['shop_name']=self.shop_name
result['shop_id']=self.shop_id
result['spu_id']=self.spu_id
result['mk_price']=self.mk_price
result['vender_id']=self.vender_id
result['find']=self.find
return json.dumps(result,cls=DecimalEncoder, ensure_ascii=False)
class Meta:
managed = False
db_table = 'goods'
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o,decimal.Decimal):
return float(o)
goods/urls
from django.urls import path
from .views import GoodsCategoryAPIView
urlpatterns = [
path("category//" ,GoodsCategoryAPIView.as_view()),
]
goods/views
from rest_framework.views import APIView
# APIView 继承了View
# 获取商品分类的接口
#访问方式 http://localhost:8000/goods/category/1
from apps.goods.models import Goods
from utils import ResponseMessage
class GoodsCategoryAPIView(APIView):
def get(self,request,category_id,page):
current_page = (page-1)*20
end_data = page*20
category_data = Goods.objects.filter(type_id=category_id).all()[current_page:end_data]
result_list=[]
for m in category_data:
result_list.append(m.__str__())
return ResponseMessage.GoodsResponse.success(result_list)
urls
from django.contrib import admin
from django.urls import path, include
from apps.menu.views import GoodsMainMenu,GoodsSubMenu
urlpatterns = [
path("admin/", admin.site.urls),
path("main_menu/", GoodsMainMenu.as_view()),
path("sub_menu/", GoodsSubMenu.as_view()),
path("goods/",include("goods.urls"))
]
setting
# 静态文件服务器配置
IMAGE_URL = "http://localhost:8000/static/product_images/"
使用商品表的su_id 查询
在商品分类中任意点击一个商品进入就能看到该商品的商品详情
goods/views.py
class GoodsDetailAPIView(APIView):
def get(self,request,sku_id):
print(sku_id)
goods_data = Goods.objects.filter(
sku_id=sku_id
).first()
# 进行序列化的动作 序列化的参数时instance, 反序列化的参数就是data
result = GoodsSerializer(instance=goods_data)
return ResponseMessage.GoodsResponse.success(result.data)
goods/urls
path("" ,GoodsDetailAPIView.as_view()),
goods/serializers.py
from rest_framework import serializers
from apps.goods.models import Goods
from muxi_shop_back.settings import IMAGE_URL
class GoodsSerializer(serializers.ModelSerializer):
# 这里边写的字段就是你想要进行序列化时处理的字段
# name = serializers.CharField()
# 对序列化中的图片做处理
image = serializers.SerializerMethodField()
# 对序列化中的日期做处理
create_time = serializers.DateTimeField("%Y-%m-%d %H:%M:%S")
# 自动调用该方法 把 new_image_path 赋值给image 比如给序列化字段image做处理image前面加get
def get_image(self,obj):
new_image_path = IMAGE_URL + obj.image
return new_image_path
class Meta:
model = Goods
fields = "__all__"
class Meta:
# 指定序列化的类
model = Goods
# 序列化所有的字段
fields = "__all__"
cart/views
from django.http import HttpResponse
from rest_framework.views import APIView
from apps.cart.models import Cart
from apps.cart.serializers import CartSerializer
class CartAPIView(APIView):
# 购物车应该登录之后才能访问
def post(self,request):
request_data = request.data
email = request_data.get("email")
sku_id = request_data.get('sku_id')
nums = request_data.get('nums')
# 判断数据是否存在 如果存在就更新,如果不存在就插入
data_exists = Cart.objects.filter(email=email,is_delete = 0,sku_id=sku_id)
# 存在即更新
if data_exists.exists():
exists_cart_data = data_exists.get(email=email,is_delete = 0,sku_id=sku_id)
new_nums = nums + exists_cart_data.nums
request_data["nums"] = new_nums
# 反序列化 json转对象
cart_ser = CartSerializer(data=request_data)
cart_ser.is_valid(raise_exception=True)
# 更新
Cart.objects.filter(
email=email, is_delete=0, sku_id=sku_id
).update(**cart_ser.data)
return ResponseMessage.CartResponse.success("更新成功")
else:
# 不存在插入
cart_ser = CartSerializer(data=request_data)
cart_ser.is_valid(raise_exception=True)
Cart.objects.create(**cart_ser.data)
return ResponseMessage.CartResponse.success("插入成功")
cart/urls
from django.urls import path
from .views import CartAPIView
urlpatterns = [
path("",CartAPIView.as_view()),
]
cart/serializers.py
from rest_framework import serializers
from apps.cart.models import Cart
class CartSerializer(serializers.ModelSerializer):
sku_id = serializers.CharField(required=True)
# email本身设置的是唯一的 所以这里重新设置一下覆盖掉
email = serializers.CharField(required=True)
class Meta:
model = Cart
fields = "__all__"
cart/models
from django.db import models
# Create your models here.
class Cart(models.Model):
id = models.AutoField(primary_key=True,null=False,unique=True)
email = models.CharField(null=False,max_length=255,unique=True)
sku_id = models.CharField(null=False,max_length=255,unique=True)
nums = models.IntegerField()
is_delete = models.IntegerField()
class Meta:
db_table="shopping_cart"
cart/views
def get(self, request):
email = request.GET.get("email")
cart_result = Cart.objects.filter(email=email,is_delete=0)
# many=True 返回多条
cart_ser = CartSerializer(instance=cart_result,many=True)
# return JsonResponse(cart_ser.data,safe=False)
return ResponseMessage.CartResponse.success(cart_ser.data)
cart/views
class CartAPIView(APIView):
# 购物车应该登录之后才能访问
def post(self, request):
request_data = request.data
email = request_data.get("email")
sku_id = request_data.get('sku_id')
nums = request_data.get('nums')
is_delete = request_data.get('is_delete')
# 判断数据是否存在 如果存在就更新,如果不存在就插入
data_exists = Cart.objects.filter(email=email, is_delete=0, sku_id=sku_id)
# 存在即更新
if data_exists.exists():
exists_cart_data = data_exists.get(email=email, is_delete=0, sku_id=sku_id)
if is_delete == 0:
new_nums = nums + exists_cart_data.nums
request_data["nums"] = new_nums
elif is_delete == 1:
new_nums = nums + exists_cart_data.nums
# 反序列化 json转对象
cart_ser = CartSerializer(data=request_data)
cart_ser.is_valid(raise_exception=True)
# 更新
Cart.objects.filter(
email=email, is_delete=0, sku_id=sku_id
).update(**cart_ser.data)
if is_delete == 0:
return ResponseMessage.CartResponse.success("更新成功")
elif is_delete == 1:
return ResponseMessage.CartResponse.success("删除成功")
else:
# 不存在插入
cart_ser = CartSerializer(data=request_data)
cart_ser.is_valid(raise_exception=True)
Cart.objects.create(**cart_ser.data)
return ResponseMessage.CartResponse.success("插入成功")