Django e-commerce function
1, Order
-
Order logic
Login users can browse products
The product details page purchases immediately and generates an order. The order status is unpaid
Add goods to the shopping cart, view the shopping cart, select the specified goods, purchase immediately and generate an order. The order status is unpaid
Settle the order using Alipay. The order status is changed to paid
-
Model creation
class Cart(models.Model): """Shopping Cart""" goods = models.ForeignKey(to=Goods, on_delete=models.CASCADE) # Commodity count = models.IntegerField() # quantity buyer = models.ForeignKey(to=Buyer, on_delete=models.CASCADE) # User def __str__(self): return self.buyer.name + '-' + self.goods.name class Meta: db_table = 'cart' class Order(models.Model): """order""" id = models.CharField(max_length=128, primary_key=True) # Order id buyer = models.ForeignKey(to=Buyer, on_delete=models.CASCADE) # user paymethod = models.IntegerField(default=3) # Payment method 1: cash on delivery 2: wechat payment 3: Alipay 4: UnionPay payment createtime = models.DateTimeField() # Creation time # Redundancy. For convenience of use, partial redundancy is allowed totalcount = models.IntegerField() # Quantity of goods totalprice = models.FloatField() # Total price of goods freight = models.IntegerField() # Order freight status = models.IntegerField(default=1) # Order status 1: to be paid 2: to be shipped 3: to be received 4: to be evaluated 5: completed tradeno = models.CharField(max_length=64, null=True) # Transaction number tradetime = models.DateTimeField(null=True) # Trading time # Record receipt information name = models.CharField(max_length=64) # Receiving user name postcode = models.CharField(max_length=64) # Receiving zip code phone = models.CharField(max_length=64) # Receiving telephone address = models.CharField(max_length=64) # Receiving address class Meta: db_table = 'order' class OrderDetail(models.Model): """order details """ order = models.ForeignKey(to=Order, on_delete=models.CASCADE) # Order goods = models.ForeignKey(to=Goods, on_delete=models.CASCADE) # Commodity count = models.IntegerField() # Quantity of goods price = models.FloatField() # commodity price name = models.CharField(max_length=64) # Trade name picture = models.ImageField() # Product picture unite = models.CharField(max_length=64) # Commodity unit class Meta: db_table = 'orderdetail'
-
Add commodity data in the background
-
Generate order
The process is as follows: add shopping cart - > settlement - > generate order
2, Shopping cart
- Model building
1. Add shopping cart
Click Add to shopping cart and use ajax to add asynchronously, prompting "add successfully, wait in shopping cart"
If it is the same product and the quantity increases, there is no need to add data
1. What does the front end do?
Sending parameters: id and quantity of goods
2. What does the backend do?
Accept parameters, add shopping cart and modify commodity inventory (judge whether the inventory is sufficient)
-
Front end operation
- Modify the page and select any position in the page as long as it is convenient to obtain
<p class="col-xs-3"><a goods_id="{{ goods.id }}" class="btn btn-danger btn-lg" href="bootstrap_cart.html" id="my_cart_add" role="button">add to cart</a></p> {% csrf_token %}
- Send ajax asynchronous requests and give different prompts according to the back-end response content
<script> //Add shopping cart, click event, $("#my_cart_add").click(function () { //Product id, attr get attribute var goods_id = $(this).attr("goods_id") //Product quantity, val gets the input value var goods_num = $("#my_goods_num").val() //csrf, obtained according to the name attribute var csrfmiddlewaretoken = $("[name=csrfmiddlewaretoken]").val() //Send asynchronous request $.ajax({ url: "/cart/add/",//route method:"post",//post request data: {//parameter goods_id:goods_id, goods_num:goods_num, csrfmiddlewaretoken:csrfmiddlewaretoken//To prevent csrf interception, 1. Add a csrf tag 2. Obtain a value }, success: function (data) {//Successful callback function console.log(data) if(data["code"]==0){ alert("Add successfully, wait in the shopping cart~") }else if(data["code"]==1){ alert("Incomplete data~") }else if(data["code"]==2){ alert("Insufficient inventory~") }else if(data["code"]==3){ alert("Abnormal kiss~") } }, error:function () { alert("error...") } }) //return false cancel the default function a tag and no longer jump return false }) </script>
-
Back end operation
- route
# Shopping cart - add path('cart/add/', buyer_view.cart_add),
- view
@buer_login_verify def cart_add(request): """Shopping Cart-add to""" # Preparing data 0 means success, 1 means incomplete data, 2 means insufficient inventory, 3 means abnormal server data = {"code": 0} try: if request.method == "POST": # Receive parameters goods_id = request.POST.get("goods_id") goods_num = request.POST.get("goods_num") # query goods = Goods.objects.get(pk=goods_id) # Judgment - not empty if not all([goods_id, goods_num]): # Incomplete data data["code"] = 1 # response return JsonResponse(data) # String to number goods_num = int(goods_num) # Judgment - inventory if goods.number < goods_num: # Incomplete data data["code"] = 2 # response return JsonResponse(data) # Query current user buyer = Buyer.objects.filter(name=request.session.get("buyer_logined")).first() # Determine whether the item is already in the shopping cart cart = Cart.objects.filter(goods=goods).first() if cart: # This item is already in the shopping cart cart.count += goods_num else: # This item is not in the shopping cart # create object cart = Cart() # Assignment attribute cart.goods = goods cart.buyer = buyer cart.count = goods_num # Add / modify cart.save() # Commodity inventory modification, sales volume goods.number -= goods_num goods.sale += goods_num goods.save() # response return JsonResponse(data) except Exception as ex: print("Exception:", ex) data = {"code": 3} return JsonResponse(data)
2. View shopping cart
Query all shopping information and render
- route
# Shopping cart - List path('cart/list/', buyer_view.cart_list),
- view
@buer_login_verify def cart_list(request): """Shopping Cart-list""" # Current login user buyer = Buyer.objects.filter(name=request.session.get("buyer_logined")).first() # Query all shopping carts of the current user cart_list = Cart.objects.filter(buyer=buyer).order_by("-id") # Render return render(request, "ft/bootstrap_cart.html", locals())
3. Shopping cart initiated settlement
- route
# Submit order page path('order/place/', buyer_view.order_place),
- view
@buer_login_verify def order_place(request): """Submit order page""" # Receive 1 Parameter get and multiple getlist get cart_ids = request.POST.getlist("ids") if not all([cart_ids]): return HttpResponse("Incomplete data") # lookup cart_list = Cart.objects.filter(id__in=cart_ids) # total totle_count = 0 # Total price totle_price = 0 for cart in cart_list: totle_count += cart.count totle_price += cart.goods.price * cart.count # freight freight = 10 # Actual payment totle_actual = totle_price + freight # Query the default harvest address of the current user receiver = Receiver.objects.filter(buyer__name=request.session.get("buyer_logined"), isdefault=1).first() # Render return render(request, "ft/place_order.html", locals())
4. Place an order
Add order table, add order details and delete shopping cart
1. Front end sending parameters: address id, payment method number, shopping cart ids
2. Back end: receive parameters, add order, add order details and delete shopping cart
Template: add form and hidden. Remember to add the name attribute of the input tag
- route
# Order addition - order placement path('order/add/', buyer_view.order_add),
- view
@buer_login_verify def order_add(request): """Order addition-place an order""" # judge if request.method == "POST": # Receive parameters receiver_id = request.POST.get("receiver_id") pay_method = request.POST.get("pay_method") cart_ids = request.POST.getlist("cart_ids") # lookup cart_list = Cart.objects.filter(id__in=cart_ids) receiver = Receiver.objects.get(pk=receiver_id) buyer = Buyer.objects.filter(name=request.session.get("buyer_logined")).first() # total totle_count = 0 # Total price totle_price = 0 for cart in cart_list: totle_count += cart.count totle_price += cart.goods.price * cart.count # freight freight = 10 # Create order object order = Order() # Attribute assignment order.id = product_order_id() order.buyer = buyer order.createtime = datetime.now() order.totalcount = totle_count order.totalprice = totle_price order.freight = freight order.status = 1 order.name = receiver.name order.postcode = receiver.postcode order.phone = receiver.phone order.address = receiver.address # Add order object order.save() # Cycle new order details for cart in cart_list: # create object orderdetail = OrderDetail() # Attribute assignment orderdetail.order = order orderdetail.goods = cart.goods orderdetail.count = cart.count orderdetail.price = cart.goods.price orderdetail.name = cart.goods.name orderdetail.picture = cart.goods.picture orderdetail.unite = cart.goods.unite # newly added orderdetail.save() # Delete shopping cart object cart_list.delete() # redirect return redirect("/user/center/")