【发布时间】:2020-01-11 14:30:41
【问题描述】:
我想重构或集成旧 Django 项目中的一些旧 Django 代码。一切都很好,直到添加到购物车选项或查看。我不知道我是否遗漏了什么,因为我只是在编写代码而不是工作程序或步骤。跟随它是如此简单。但我现在有筹码。
购物车模型views.py文件
from django.shortcuts import render
from django.views.generic.base import TemplateView
from django.shortcuts import redirect
from django.contrib.auth.forms import AuthenticationForm
from django.views.generic.edit import FormMixin
from django.urls import reverse
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from . import models
from products import models as product_models
class CartCreateView(TemplateView, APIView):
""" add item to cart request handler """
template_name = 'carts/view.html'
@staticmethod
def _process_cart(item_id, quantity, delete, request):
cart = None
is_deleted = False
if 'cart_id' not in request.session:
cart = models.Cart.objects.create()
request.session['cart_id'] = cart.id
if cart == None:
cart = models.Cart.objects.get(id=request.session['cart_id'])
if request.user.is_authenticated():
cart.user = request.user
cart.save()
product_models.Variation.objects.get(id=item_id)
cart_item, created = models.CartItem.objects.get_or_create(cart=cart, item_id=item_id)
if created or quantity != 1:
cart_item.quantity = quantity
else:
cart_item.quantity += 1;
if delete in ['y','yes', 'true', 'True']:
is_deleted = True
cart_item.delete()
else:
cart_item.save()
return cart, is_deleted, cart_item
def get(self, request):
try:
item_id = request.GET.get('item')
quantity = request.GET.get('qty', 1)
delete = request.GET.get('delete', 'n')
cart, is_deleted, cart_item = self._process_cart(item_id, int(quantity), delete, request)
cart_count = cart.total_count
request.session['cart_count'] = cart_count
return Response({'success': True,
'deleted': is_deleted,
'count': cart.count,
'item_total': cart_item.item_total,
'cart_price': cart.cart_price,
'cart_count': cart_count}, status=status.HTTP_200_OK)
except Exception as error:
print(error)
class CartDetailView(TemplateView):
template_name = 'carts/view.html'
def get(self, request):
if 'cart_id' not in request.session:
return redirect('/')
cart = models.Cart.objects.get(id=request.session['cart_id'])
return render(request, self.template_name, {'object': cart })
这是我的模板,其中有一个按钮和一些 jquery 实现,当我单击该按钮时应该可以工作。但是会出现上述错误。
也许问题在于使用 APIVIew 和 django_rest 框架。我还不熟悉 DRF。如果您认为使用基于函数的视图或其他任何不同的视图可以实现所需的结果,请建议我。
这是我的模板 product_page.html
{% extends "base.html" %}
{% block jquery%}
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("Yeah!");
} else {
// jQuery is not loaded
alert("Doesn't Work");
}
}
function setPrice(){
var price = $('.variation-select option:selected').data('price');
var salePrice = $('.variation-select option:selected').data('sale-price');
if(salePrice && salePrice !== 'None'){
$('#price').html(` <h3>${salePrice}<small style="color:red;text-decoration:line-through;">${price}</small><h3>`);
}
else{
$('#price').text(price);
}
}
$('.variation-select').change(function(){
setPrice();
})
$('#add-to-cart').click(function(event){
event.preventDefault();
var formData = $('#cart-form').serialize();
$.ajax({
url: "{% url 'create_cart' %}" + '?' + formData,
type: 'GET',
success: function(response){
console.log(response);
$('#cart-count-badge').text(response.cart_count);
$('.container.flash-msg').fadeIn();
window.setTimeout(function(){
$('.container.flash-msg').fadeOut();
}, 2000);
},
error: function(response, error){
}
});
});
{% endblock %}
{% block content %}
<style>
.flash-msg {
position: absolute;
top: 23px;
z-index: 2000;
width: 100%;
display: none;
}
</style>
<div class="container flash-msg">
<div class="col-sm-3 col-sm-offset-8">
<div class="alert alert-success" role="alert">
<strong>Item added to cart</strong>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<h3>{{product.title}}</h3>
{% if product.get_image_url %}
<div>
<img src="{{product.get_image_url}}" class="img-responsive">
</div>
{% endif %}
<div>
<p class="lead">{{product.description}}</p>
</div>
</div>
<div class="col-sm-4">
<form id="cart-form" method="GET" action="{% url 'create_cart' %}">
<!-- show product variation -->
{% if product.variation_set.all.count > 1 %}
<h3 id="price">{{product.variation_set.first.price}}
{% if product.variation_set.first.sale_price %}
<small id="sale-price" style="color:red;text-decoration:line-through;">{{product.variation_set.first.sale_price}}</small>
{% endif %}
</h3>
<select name="item" class="form-control variation-select">
{% for variation in product.variation_set.all %}
<option data-sale-price="{{variation.sale_price}}" data-price="{{variation.price}}" value="{{variation.id}}">{{variation}}</option>
{% endfor %}
</select>
{% else %}
<h3 id="price">{{product.variation_set.first.price}}</h3>
<input type="hidden" name="item" value="{{product.variation_set.first.id}}" />
{% endif %}
<br>
<button id="add-to-cart" class="btn btn-primary" href="">Add To Cart</button>
</form>
<br>
<br>
{% if related_products %}
<h4>Related products</h4>
<div class="row">
{% for product in related_products %}
<div class="col-xs-5">
{% include "products/product_thumbnail.html" with product=product %}
</div>
{% endfor %}
</div>
{% endif %}
</div>
</div>
{% endblock %}
【问题讨论】:
-
在异常情况下,您只需打印错误并且不会从您的
get方法返回任何内容。您需要返回某种响应
标签: jquery django django-rest-framework django-views e-commerce