Django:使用jQuery添加减去推车按钮
我的模型:
class Cart(models.Model):
cart_id = models.CharField(max_length=255, blank=True)
date_added = models.DateField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Cart'
def __str__(self):
return self.cart_id
class CartItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
def total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product
我的观点:
def _cart_id(request):
cart_id = request.session.session_key
if not cart_id:
cart_id = request.session.create()
return cart_id
def add_to_cart(request, product_id):
product = Product.objects.get(id=product_id)
try:
my_cart = Cart.objects.get(cart_id=_cart_id(request))
my_cart.save()
except ObjectDoesNotExist:
my_cart = Cart.objects.create(
cart_id=_cart_id(request),
)
my_cart.save()
try:
cart_item = CartItem.objects.get(product=product, cart=my_cart)
cart_item.quantity += 1
cart_item.save()
except ObjectDoesNotExist:
cart_item = CartItem.objects.create(
product=product,
cart=my_cart,
quantity=1,
)
cart_item.save()
return redirect('cart')
def cart(request, sub_total=0, quantity=0, cart_items=None, sale_tax=0):
try:
current_cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=current_cart, is_active=True)
for item in cart_items:
sub_total += (item.product.price * item.quantity)
quantity += item.quantity
sale_tax = round((7 * sub_total)/100, 2)
except ObjectDoesNotExist:
pass
context = {
'sub_total': sub_total,
'quantity': quantity,
'cart_items': cart_items,
'sale_tax': sale_tax,
'grand_total': sale_tax + sub_total,
}
return render(request, 'cart.html', context)
我的模板部分:
<tbody>
{% for item in cart_items %}
<tr>
<td class="product-thumbnail"><a href="{{ item.product.get_url }}"><img src="{{ item.product.image_1.url }}" alt=""></a></td>
<td class="product-name"><a href="{{ item.product.get_url }}">{{ item.product.product_name }}</a></td>
<td class="product-price"><span class="amount">${{ item.product.price }}</span></td>
<td class="product-quantity">
<div class="cart-plus-minus"><input type="text" value="{{ item.quantity }}" /></div>
</td>
<td class="product-subtotal"><span class="amount">${{ item.total }}</span></td>
<td class="product-remove"><a href="#"><i class="fa fa-times"></i></a></td>
</tr>
{% endfor %}
</tbody>
我的jQuery:
$(".cart-plus-minus").append('<div class="dec qtybutton">-</div><div class="inc qtybutton">+</div>');
$(".qtybutton").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
我不是一个jQuery的家伙,所以当客户按apl a Plus或负按钮时,我对如何更新Plus或Minus产品的总价格感到困惑 - jQuery将接管。在django中,我的购物车上的urlpattern就是这样:
urlpatterns = [
path('', views.cart, name='cart'),
path('add_to_cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
]
这意味着,如果客户碰到负号或加号,则推车中产品的数量需要增加或减少一个 - 我需要的是拥有加号以重定向客户访问已编码的add_to_cart视图,此视图会自动将客户重新定向到购物车中,以更新购物车的项目数量。我如何在我发布的代码的jQuery位中实现这一目标?它必须是我发布的jQuery代码的确切点,因为它随附了模板。在Django,在任何常规模板中,应该很容易做到这样的事情:
<a href="{% url 'add_to_cart' item.product.id %}" class="btn btn-light" type="button" id="button-minus"> <i class="fa fa-plus"></i></a>
但是您如何使用jQuery做到这一点?
My models:
class Cart(models.Model):
cart_id = models.CharField(max_length=255, blank=True)
date_added = models.DateField(auto_now_add=True)
class Meta:
verbose_name_plural = 'Cart'
def __str__(self):
return self.cart_id
class CartItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
def total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product
My views:
def _cart_id(request):
cart_id = request.session.session_key
if not cart_id:
cart_id = request.session.create()
return cart_id
def add_to_cart(request, product_id):
product = Product.objects.get(id=product_id)
try:
my_cart = Cart.objects.get(cart_id=_cart_id(request))
my_cart.save()
except ObjectDoesNotExist:
my_cart = Cart.objects.create(
cart_id=_cart_id(request),
)
my_cart.save()
try:
cart_item = CartItem.objects.get(product=product, cart=my_cart)
cart_item.quantity += 1
cart_item.save()
except ObjectDoesNotExist:
cart_item = CartItem.objects.create(
product=product,
cart=my_cart,
quantity=1,
)
cart_item.save()
return redirect('cart')
def cart(request, sub_total=0, quantity=0, cart_items=None, sale_tax=0):
try:
current_cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=current_cart, is_active=True)
for item in cart_items:
sub_total += (item.product.price * item.quantity)
quantity += item.quantity
sale_tax = round((7 * sub_total)/100, 2)
except ObjectDoesNotExist:
pass
context = {
'sub_total': sub_total,
'quantity': quantity,
'cart_items': cart_items,
'sale_tax': sale_tax,
'grand_total': sale_tax + sub_total,
}
return render(request, 'cart.html', context)
My template portion:
<tbody>
{% for item in cart_items %}
<tr>
<td class="product-thumbnail"><a href="{{ item.product.get_url }}"><img src="{{ item.product.image_1.url }}" alt=""></a></td>
<td class="product-name"><a href="{{ item.product.get_url }}">{{ item.product.product_name }}</a></td>
<td class="product-price"><span class="amount">${{ item.product.price }}</span></td>
<td class="product-quantity">
<div class="cart-plus-minus"><input type="text" value="{{ item.quantity }}" /></div>
</td>
<td class="product-subtotal"><span class="amount">${{ item.total }}</span></td>
<td class="product-remove"><a href="#"><i class="fa fa-times"></i></a></td>
</tr>
{% endfor %}
</tbody>
My JQuery:
$(".cart-plus-minus").append('<div class="dec qtybutton">-</div><div class="inc qtybutton">+</div>');
$(".qtybutton").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
I'm not a JQuery guy, and so I'm confused of how to update the plus or minus product's total price when a customer hit a plus or a minus button - which JQuery will take over. In Django, my urlpatterns for the cart is like this:
urlpatterns = [
path('', views.cart, name='cart'),
path('add_to_cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
]
This means if a customer hits the minus or plus sign, the product's quantity in the cart needs to increase or decrease by one - what I need is to have the plus sign to redirect the customer to add_to_cart's view, which is already coded, and this view, automatically redirects the customer back to the cart to update the cart's item quantity. How do I actually accomplish this in the JQuery bit of code I posted? It has to be the exact bit of JQuery code I posted since it comes with the template. In Django, in any regular template, it should be easily done like this:
<a href="{% url 'add_to_cart' item.product.id %}" class="btn btn-light" type="button" id="button-minus"> <i class="fa fa-plus"></i></a>
But how do you do this with JQuery?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想出了答案并使其起作用。但是,现在我正在关注XSS攻击安全问题。像我在解决问题时所做的那样,编码是否安全?
模板部分:
jQuery部分:
我已修复的部分和现在正常工作的部分是:
现在,我想知道,如果此修复程序到位,这将成为安全漏洞?根据Django的文档:
参数:标签的html“ id”。
例如:
{{value | json_script:“ hello-data”}}
如果值是字典{'hello':'world'},则输出将为:
{"hello": "world"}
在这样的javascript中访问所得数据
可以 );
XSS攻击可以通过逃避角色“&lt;”,“&gt;”来减轻XS攻击。和“&amp;”。例如,如果值为{'Hello':'World&amp;'},则输出是:
{"hello": "world\\u003C/script\\u003E\\u0026amp;"}
这与禁止页面内部执行的严格内容安全策略兼容。它还保持被动数据和可执行代码之间的干净分离。
I figured out the answer and made it work. Nonetheless, now I'm concerning about XSS attacks security issue. Is it safe to code like how I just did in solving my issue?
The template portion:
jQuery portion:
The part that I fixed and it's now working is where:
Now, I'm wondering, will this be a security vulnerability if this fix is in place? According to Django's doc:
Argument: HTML “id” of the tag.
For example:
{{ value|json_script:"hello-data" }}
If value is the dictionary {'hello': 'world'}, the output will be:
{"hello": "world"}
The resulting data can be accessed in JavaScript like this:
const value = JSON.parse(document.getElementById('hello-data').textContent);
XSS attacks are mitigated by escaping the characters “<”, “>” and “&”. For example if value is {'hello': 'world&'}, the output is:
{"hello": "world\\u003C/script\\u003E\\u0026amp;"}
This is compatible with a strict Content Security Policy that prohibits in-page script execution. It also maintains a clean separation between passive data and executable code.