异常值:对于带有基数10的int()的无效文字:''

时间:2018-04-13 07:28:58

标签: django django-models

在尝试从卡中删除项目时,我得到了这个:

  

例外值:

     

对于基数为10的int()的无效文字:,当我尝试删除项目时   从卡片中显示异常值:int()的文字无效   基地10:,当我尝试从卡中删除项目时显示异常   值:对于基数为10的int()的无效文字:,当我尝试删除时   卡中的项目显示异常值:int()的文字无效   基数10:,

推车/ views.py

from django.shortcuts import render,redirect
from products.models import Product
from .models import Cart


def cart_home(request):
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    return render(request, "carts/home.html", {"cart": cart_obj})

def cart_update(request):
    product_id=request.POST.get('product_id')
    if product_id is not None:
        try:
            product_obj = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            print("Show message to user Product is gone")
            return redirect("cart:home")
        cart_obj, new_obj = Cart.objects.new_or_get(request)
        if product_obj in cart_obj.products.all():
            cart_obj.products.remove(product_obj)
        else:
            cart_obj.products.add(product_obj)
        #request.session['cart_items'] = cart_obj.products.count()
    #cart_obj.products.remove(product_obj)
    return redirect("cart:home")

更新cart.html

<form method="POST" action="{% url "cart:update" %}" class= "form ">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{ product.id }}"/>
    {% if in_cart %}
        <button type="submit" class="btn btn-link btn-sm " style="padding: 0px; cursor: pointer">Remove?</button>
    {% else %}
        {% if product in cart.products.all %}
            In cart<button type="submit" class="btn-btn-link">Remove?</button>
        {% else %}
            <button type='submit'  class='btn btn-success'>Add to cart</button>
        {% endif %}
    {% endif %}

    </form>

home.html的

{% extends "base.html" %}
{%  block content %}
    <h1>Cart</h1>
    {% if cart.products.exists %}

    <table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Product Name</th>
      <th scope="col">Product Price</th>
    </tr>
  </thead>
  <tbody>
  {% for product in cart.products.all %}
    <tr>
      <th scope="row">{{ forloop.counter }}</th>
        <td><a href="{{ product.get_absolute_url }}">{{ product.title }}</a>
        {% include "product/snippets/update-cart.html" with product=object cart=cart in_cart=True %}
        </td>
      <td>{{ product.price }}</td>
    </tr>
  {% endfor %}
    <tr>
      <td colspan="2"></td>
      <td><b>Subtotal</b>{{ cart.subtotal }}</td>
    </tr>
    <tr>
      <td colspan="2"></td>
      <td><b>Total</b>{{ cart.total }}</td>
    </tr>
  </tbody>
</table>
    {% else %}
    <p class="lead">Card is empty</p>
    {% endif %}
{%  endblock %}

卡/ models.py

from django.db import models
from django.conf import settings
from decimal import Decimal
from products.models import Product
from django.db.models.signals import pre_save, post_save, m2m_changed


User=settings.AUTH_USER_MODEL

class CartManager(models.Manager):
    def new_or_get(self, request):
        cart_id = request.session.get("cart_id", None)
        qs = self.get_queryset().filter(id=cart_id)
        if qs.count() == 1:
            new_obj = False
            cart_obj = qs.first()
            if request.user.is_authenticated and cart_obj.user is None:
                cart_obj.user = request.user
                cart_obj.save()
        else:
            cart_obj = Cart.objects.new(user=request.user)
            new_obj = True
            request.session['cart_id'] = cart_obj.id
        return cart_obj, new_obj

    def new(self, user=None):
        user_obj = None
        if user is not None:
            if user.is_authenticated:
                user_obj = user
        return self.model.objects.create(user=user_obj)

class Cart(models.Model):
    user=models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE)
    products=models.ManyToManyField(Product,blank=True)
    subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
    total=models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
    updated = models.DateTimeField(auto_now=True)
    timestamp=models.DateTimeField(auto_now_add=True)
    objects = CartManager()

    def __str__(self):
        return str(self.id)

def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs):
    if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
        products = instance.products.all()
        total = 0
        for x in products:
            total += x.price
        if instance.subtotal != total:
            instance.subtotal = total
            instance.save()

m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through)


def pre_save_cart_receiver(sender,instance,*args,**kwargs):
    instance.total=instance.subtotal + 10
pre_save.connect(pre_save_cart_receiver,sender=Cart)

detail.html

{% extends "base.html" %}
{% block content %}
    <div class="row">
        <div class="col-12 col-md-6">
        {{ object.timestamp|timesince }} ago
        <h2>{{ object.timestamp }}</h2><br/>
    {{ object.description}}<br/>
    {% if object.image %}
        <img src='{{ object.image.url}}' class="img-fluid"/>
    {% endif %}
     </div>
    <div class="col-12 col-md-6">
    {% include "product/snippets/update-cart.html" with product=object cart=cart %}

    </div>
    </div>
{% endblock content %}

1 个答案:

答案 0 :(得分:0)

Product查询管理器在给出id时期望带有str键的整数值(request.POST是一个类似dict的对象,其值为str
所以你需要做的是,改变

# other code
try:
    product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
    # other code


# other code 
try:
    product_obj = Product.objects.get(id=int(product_id)) # <<<<<<< Change is here
except Product.DoesNotExist:
    # other code