Django:使用jQuery添加减去推车按钮

发布于 2025-01-31 00:25:36 字数 4982 浏览 1 评论 0原文

我的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

り繁华旳梦境 2025-02-07 00:25:36

我想出了答案并使其起作用。但是,现在我正在关注XSS攻击安全问题。像我在解决问题时所做的那样,编码是否安全?

模板部分:

<div class="cart-plus-minus"><input type="text" value="{{ item.quantity }}"/>
                                            <input type="hidden" id="Url" data-url="{% url 'add_to_cart' item.product.id %}" />
                                            </div>

jQuery部分:

<script>
  // // // // ////////////////////////////////////////////////////
  // // // // // 21. Cart Plus Minus Js

  $(".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;
      window.location.href = $("#Url").attr("data-url")   
    } else {
      // Don't allow decrementing below zero
      if (oldValue > 0) {
        var newVal = parseFloat(oldValue) - 1;
      } else {
        newVal = 0;
      }
    }
    $button.parent().find("input").val(newVal);
  });
    </script>

我已修复的部分和现在正常工作的部分是:

window.location.href = $("#Url").attr("data-url")

现在,我想知道,如果此修复程序到位,这将成为安全漏洞?根据Django的文档:

json_script¶
安全地输出一个python对象为JSON,包裹在标签中,可以与JavaScript一起使用。

参数:标签的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:

<div class="cart-plus-minus"><input type="text" value="{{ item.quantity }}"/>
                                            <input type="hidden" id="Url" data-url="{% url 'add_to_cart' item.product.id %}" />
                                            </div>

jQuery portion:

<script>
  // // // // ////////////////////////////////////////////////////
  // // // // // 21. Cart Plus Minus Js

  $(".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;
      window.location.href = $("#Url").attr("data-url")   
    } else {
      // Don't allow decrementing below zero
      if (oldValue > 0) {
        var newVal = parseFloat(oldValue) - 1;
      } else {
        newVal = 0;
      }
    }
    $button.parent().find("input").val(newVal);
  });
    </script>

The part that I fixed and it's now working is where:

window.location.href = $("#Url").attr("data-url")

Now, I'm wondering, will this be a security vulnerability if this fix is in place? According to Django's doc:

json_script¶
Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文