Django 购物车模板

Posted rivend

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 购物车模板相关的知识,希望对你有一定的参考价值。

技术图片

 

 

url

from django.contrib import admin
from django.urls import path, re_path
from django.urls import include

urlpatterns = [
    re_path(r^admin/, admin.site.urls),
    re_path(‘^api/(?P<version>[v1|v2]w+)/‘, include(‘app01.urls‘)),
]

 

from django.urls import path, re_path
from django.urls import include
from app01.views import account, coursehost, newspapers, shoppingcar

urlpatterns = [
    re_path(login/$, account.LoginView.as_view()),

    re_path(course/$, coursehost.CourseView.as_view({"get": "list"})),
    re_path(course/(?P<pk>d+)/$, coursehost.CourseView.as_view({"get": "retrieve"})),
    re_path(rcoursecategory/$, coursehost.CourseCategoryView.as_view({get: list})),

    re_path(r‘shoppingcar/$‘, shoppingcar.ShoppingCarViewSet.as_view()),

]

 

视图:

"""
* coding: utf-8

CreateTime:2019/12/20
Version: v1
DocName: shoppingcar.py
Edit: Riven

Effect: shoppingcar data

SourceStorageLocation: RivenShop / app01 / views / Shoppingcar.py
Modify and add function record:
        ModifyTime:
            1.
            2.
        Add function Time :
            1.
            2.

"""
from app01 import models
from utils.response import TokenAuth
from utils.response import BaseResponse
from utils.exception import PricePolicyIncalid
from rivenshop import settings

import json

from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from django.core.exceptions import ObjectDoesNotExist


class ShoppingCarViewSet(APIView):
    authentication_classes = [TokenAuth, ]
    conn = get_redis_connection(default)

    def post(self, request, *args, **kwargs):
        """
        add course the ShoppingCar
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = BaseResponse()
        try:
            # 1. acquire user submit Course ID with PriceTactics ID
            course_id = int(request.data.get(courseid))
            policy_id = int(request.data.get(policyid))

            # 2. acquire   course ID
            course = models.Course.objects.get(id=course_id)

            # 3.acquire course all PriceTactics
            price_policy_list = course.price_policy.all()

            price_policy_dict = {}
            for item in price_policy_list:
                price_policy_dict[item.id] = {
                    "period": item.valid_period,
                    "period_display": item.get_valid_period_display(),
                    "price": item.price,
                }
            print(price_policy_dict)
            # 4. estimate  submit data whether  legitimate
            if policy_id not in price_policy_dict:
                # return error PriceTactics illegal
                raise PricePolicyIncalid("价格策略不合法")

            # 5.ShoppingCar msg add redis
            car_key = settings.SHOPPING_CAR_KEY % (request.auth.user_id, course_id)
            car_dict = {
                "titile": course.name,
                "img": course.course_img,
                "default_policy": policy_id,
                "policy": json.dumps(price_policy_dict)

            }
            self.conn.hmset(car_key, car_dict)
            ret.data = "添加成功"

        except PricePolicyIncalid as e:
            ret.code = 2001
            ret.error = e.msg

        except ObjectDoesNotExist as e:
            ret.code = 2001
            ret.error = "课程不存在"

        except Exception as e:
            ret.code = 1001
            ret.error = "获取购物车失败"
        return Response(ret.dict)

    def delete(self, request, *args, **kwargs):
        """
        Delete ShoppingCar course
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        ret = BaseResponse()
        try:
            course_id_list = request.data.get("courseids")
            key_list = [settings.SHOPPING_CAR_KEY % (request.auth.user_id, course_id,) for course_id in course_id_list]
            self.conn.delete(*key_list)
        except Exception as e:
            ret.code = 1002
            ret.error = "删除失败"

        return Response(ret.dict)

    def patch(self, request, *args, **kwargs):
        """
        Modification PriceTactics for course
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = BaseResponse()
        try:
            # 1.acquire PriceTactics ID with course ID
            course_id = int(request.data.get("courseid"))
            policy_id = str(request.data.get("policyid"))

            # 2.joint the course key
            key = settings.SHOPPING_CAR_KEY % (request.auth.user_id, course_id,)

            if not self.conn.exists(key):
                ret.code = 1002
                ret.error = "购物车中不存在此课程"
                return Response(ret.dict)
            # 3. Acquire PriceTactics data all for redis
            policy_dict = json.loads(str(self.conn.hget(key, "policy"), encoding=utf-8))

            if policy_id not in policy_dict:
                ret.code = 1003
                ret.error = "价格策略不合法"
                return Response(ret.dict)
            print(key)
            # 4.Modification ShoppingCar Course PriceTactics
            self.conn.hset(key, default_policy, policy_id)

            ret.data = "修改成功"
            print(456464165)

        except Exception as e:
            ret.code = 1004
            ret.error = "修改失败"

        return Response(ret.dict)

    def get(self, request, *args, **kwargs):
        """
        see ShoppingCar all data
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = BaseResponse()
        try:
            key_match = settings.SHOPPING_CAR_KEY % (request.auth.user_id, "*")
            course_list = []

            for key in self.conn.scan_iter(key_match, count=10):
                print(key)
                info = {
                    "title": self.conn.hget(key, titile).decode(utf-8),
                    "img": self.conn.hget(key, img).decode(utf-8),
                    "policy": json.loads(self.conn.hget(key, policy).decode(utf-8)),
                    "default_policy": self.conn.hget(key, default_policy).decode(utf-8)
                }

                course_list.append(info)

            ret.data = course_list

        except Exception as e:
            ret.code = 1002
            ret.error = "获取失败"
        return Response(ret.dict)

 

 

以上是关于Django 购物车模板的主要内容,如果未能解决你的问题,请参考以下文章

Django 购物车模板

使用 Django 创建会话和按钮,通过模板和 views.py 将产品连接到购物车

JavaScript 片段在 Django 模板中不起作用

如何在扩展另一个文件的 django 模板中使用带有动态内容的 html 块片段?

Django - 从模板内部调用带有表单的视图

Django 模板 - 嵌套字典迭代