找不到页面 (404) 没有符合给定查询的购物车

Page not found (404) No cart matches the given query

出现错误:

Page not found (404) No cart matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/change_quan?cid=1&quantity=2 Raised by: myapp.views.change_quan

当我试图在数据库中保存数量值时 我试过了,但这个错误总是出现

我的views.py

def productcart(request):
context = {}
items = cart.objects.filter(user__id=request.user.id,status=False)
context["items"] = items
if request.user.is_authenticated:
    if request.method=="POST":
       pid = request.POST["pid"]
       qty = request.POST["qty"]
       img = request.POST["img"]
       dis_price = request.POST["dis_price"]
       is_exist = cart.objects.filter(product__id=pid,user__id=request.user.id,status=False)
       if len(is_exist)>0:
           context["msg"] = "item already exist in cart"
           context["cls"] = "alert alert-warning"
       else:
          product = get_object_or_404(Product,id=pid)
          usr = get_object_or_404(User,id=request.user.id)
          c = cart(user=usr,product=product,quantity=qty,image=img,total_price=dis_price)
          c.save()
          context["msg"] = "{} Added in cart".format(product.name)
          context["cls"] = "alert alert-success"
          
else:
    context["status"] = "Please login first to add products to cart"
return render(request,'E-commerce-cart.html',context)


def get_cart_data(request):
items = cart.objects.filter(user__id=request.user.id,status=False)
sale,total,quantity=0,0,0
for i in items:
    sale+=i.product.discount
    total+=i.product.price
    quantity+=i.quantity

res={
    "total":total,"offer":sale,"quan":quantity
}
return JsonResponse(res)

def change_quan(request):
        qty = request.GET["quantity"]
        cid = request.GET["cid"]
        print(request.GET)
        cart_obj = get_object_or_404(cart,id=cid)
        cart_obj.quantity = qty
        cart_obj.save()
        return HttpResponse(1)

我的urls.py

    """emarket URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from os import name
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name='home'),
    path('shop/',views.shop,name='shop'),
    path('login/',views.create_user,name='login'),
    path('logout/',views.user_logout,name='logout'),
    path('cart/',views.productcart,name='cart'),
    path('checkout/',views.checkout,name='checkout'),
    path('product_detail/',views.product_detail,name='prodct-detail'),
    path('find_us/',views.find_us,name='find'),
    path('blog/',views.blog,name='blog'),
    path('base/',views.base),
    path('api/categories',views.all_categories,name="all_categories"),
    path('api/brand',views.brand,name="brand"),
    path('api/products',views.product_filter_api,name="product_filter_api"),
    path('user_check/',views.check_user,name="check_user"),
    path('filter_product/',views.filter_product,name="filter_product"),
    path('add_to_favourite/',views.add_to_favourite,name="add_to_favourite"),
    path('all_favourites/',views.all_favourites,name="all_favourites"),
    path('forgotpass',views.forgotpass,name="forgotpass"),
    path('resetpass',views.resetpass,name="resetpass"),
    path('get_cart_data',views.get_cart_data,name="get_cart_data"),
    path('change_quan',views.change_quan,name='change_quan'),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

我的models.py

class cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    image = models.ImageField(default=False)
    total_price=models.FloatField(default=False)
    quantity = models.IntegerField()
    status = models.BooleanField(default=False)
    added_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.user.username

我的html代码

    {% extends 'base.html' %}
{% block head %}
<style>
        .k{height: 1px;background-color: rgb(211, 207, 207);}
    .s{color:rgb(240, 240, 240);
    letter-spacing: 3px;
    font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
   font-weight: 400;}
    .cncl_icn{
        float: left;
        margin: 15px;
        padding-top: 10px;
    }
    .a:hover{
        background-color:rgba(152, 209, 255, 0.705);color: rgb(255, 255, 255);box-shadow:0px 0px 7px 7px rgba(204, 201, 201, 0.5) ;
    }
    @media screen and (max-width:680px){
        .b{opacity: 0;}
        /* .v{position: absolute;top: 5px;} */
        .s{font-size: 15px;}
        }
    @media screen and (min-width:1024px){
        .s{font-size: 20px;}
        }
</style>
{% endblock %}

{% block body %}
{% if user.is_superuser %}
<div class="container-fluid "></div>
    <h1 class="jumbotron my-5" >you are not Allowed here</h1>
{% else %}
     {% if status %}
       <h1 class="jumbotron my-5">{{status}}</h1>
     {% else %}
     {% if msg %}
     <div class="{{cls}}">{{msg}}</div>
     {% endif %}
       <div class="row v " style="margin-right: 0%;">
        <div class="col-lg-7"  >
            <div class="row text-center p-3  b" style="background-color: rgba(2, 184, 184, 0.863); background-attachment: fixed;">
                <div class="col-md-3 "> <h3 class="s">Product</h3></div>
                <div class="col-md-3 "><h3 class="s">Price</h3></div>
                <div class="col-md-3 "><h3 class="s">Qantity</h3></div>
                <div class="col-md-3 "><h3 class="s">Total</h3></div>
            </div>
            {% for i in items %}
             <div class="row a border-bottom"  id="col{{i.product.id}}">
                <div class="col-md-3 text-center " >
                   <i class="far fa-times-circle cncl_icn" id="cross{{i.product.id}}" style="font-size: 30px;"></i>
                    <img class="mt-4" src="/media/{{i.image}}" alt="check ur internet!" height="150px">
                    <a href="/product_detail/?id={{i.product.id}}" style="text-decoration: none;"><h4 class="ml-5" style="color: black;">{{i.product.name}}</h4></a>
                    <p class="ml-5">Size:{{i.product.size}} , color:{{i.product.color}}</p>
                </div>
                <div class="col-md-3 text-center mt-5">
                    {%if i.total_price < i.product.price%}
                    <del style="font-weight: bold; color: grey;" >${{i.product.price}}</del> $<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.total_price}}</p>
                    {% else %}
                    $<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.product.price}}</p>
                    {% endif %}
                </div>
                <div class="col-md-3 text-center">
                    <div class="form-group mt-4">
                        <div class="input-group">
                            <div class="input-group-btn ">
                                <button id="down" class="btn btn-default" onclick="change_quan('{{i.product.id}}','minus')"  style="font-size: 25px;background: none;border: none;font-weight: bold;">-</button>
                            </div>
                            <input type="number" id="cart{{i.product.id}}"  class="form-control text-center pt-3" value="{{i.quantity}}" style="width: 30px;border: none;font-weight: bold;background: none;">
                            <div class="input-group-btn">
                                <button id="up" class="btn btn-default" onclick="change_quan('{{i.product.id}}','plus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">+</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3 mt-5 text-center">
                    {%if i.total_price < i.product.price %}
                    $<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.total_price}}</p>
                    {% else %}
                    $<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.product.price}}</p>
                    {% endif %}
                </div>
            </div>
            <script>
                $(function() {
                    $("#cross{{i.product.id}}").hover(function() {
                        $("#cross{{i.product.id}}").toggleClass("fas fa-times-circle").toggleClass("far fa-times-circle")
                    })
                    // to remove product from cart
                    $("#cross{{i.product.id}}").confirm({
                        title: 'Confirm',
                        content: 'Are you sure to remove this product from cart',
                        theme: 'modern',
                        buttons:{

                            confirm: function() {
                            $('#col{{i.product.id}}').remove()
                        },
                            cancel: function (){}
                        }
                       
                    })
                })
            </script>  
            {% endfor %}
        </div> 
        <script>
            function grandTotal(){
                $.ajax({
                    url:"{% url 'get_cart_data' %}",
                    type:'get',
                    success:function(data){
                        p = Math.round((data.offer/data.total)*100,2)
                        $('.item_total').html("&dollar;"+data.total)
                        $('#offer').html("&dollar;"+data.offer)
                        $('#per').html("("+p+"%)")
                        $('#quantity').html(data.quan)
                        c = (data.total)-(data.offer)
                        $('#grand_Total').html("&dollar;"+c)
                    }
                })
            }
            grandTotal()

            function change_quan(id,action){
                let old = $("#cart"+id).val();
                quan = 0
                if(action=="plus"){
                    quan+=parseInt(old)+1
                    $('#total'+id).text( parseFloat($('#total'+id).text()) +  parseFloat($('#price'+id).text()))
                }
                else{
                    quan+=parseInt(old)-1
                    $('#total'+id).text( parseFloat($('#total'+id).text()) -  parseFloat($('#price'+id).text()))
                }
                $("#cart"+id).val(quan);

                $.ajax({
                    url:"{% url 'change_quan' %}",
                    type:"get",
                    data:{cid:id,quantity:quan},
                    success:function(data){
                        alert(data)
                    }
                });
            }
        </script>
         <div class="col-md-5 text-center py-5" style="background-color: rgba(255, 176, 218, 0.397);">
<div id="cartt"></div>
            <div class="row">
                    <img src="/static/Images/estore1.png" alt="" height="300px" style="margin: auto;">
            </div>
            <div class="pb-3 " style="font-size:30px;font-weight: bold;">--------------------</div>
            <h4 class="pt-3" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Total: <span style="font-size: 28px;" class="item_total"></span></h4>
            <h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Quantity: <span style="font-size: 28px;" id="quantity"></span><span style="text-transform: none;"> Items</span></h4>
            <h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">You Saved: <span style="font-size: 28px;" id="offer"></span><span class='text-success'style="font-size: 20px;" id="per"></span></h4>
            <h4 class="py-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Grand Total: <del style="font-size: 25px; color:grey;" class="item_total"></del><span style="font-size: 28px;" id="grand_Total"></span></h4>
            <h4 class="pt-3">Shipping charges will calculated at checkout</h4>
            <form class="pt-3" action=""  >
                <!-- <input type="text"  placeholder="Coupon code.." name="cod" class="mt-3 text-center" style="letter-spacing: 2px;font-size: 20px;border-radius: 25px;width: 250px;height: 47px;background-color: rgb(255, 255, 255);border:2px solid thistle;" >
               <input type="submit" class="mt-3" value="Apply Code"name="acd" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: rgb(161, 158, 158);color: rgb(255, 255, 255);" > -->
                <input  type="submit" value="CHECKOUT" name="che" class="mt-5" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: black;color: rgb(255, 255, 255);" >
            </form>
        </div> 
     </div>
     {% endif %}
</div>
{% endif %}
{% endblock %}

如果数据不存在'get_object_or_404' 将抛出 404 错误,根据您的要求您正在尝试使用主键 1 检索数据,但数据不可用 这就是您收到此错误的原因。所以请检查你 table 或尝试使用其他 pk 值

def change_quan(request):
    qty = request.GET["quantity"]
    cid = request.GET["cid"]
    print(request.GET)
    cart_obj = get_object_or_404(cart,id=cid)  # please check this cid value 
    cart_obj.quantity = qty
    cart_obj.save()
    return HttpResponse(1)

get_object_or_404 在这里不是正确的选择。由于在数据库中找不到带有 id=cid 的对象,因此引发了 404 错误。这是 get_object_or_404.

的预期行为

您是否打算使用 get_or_create 对象以防找不到试图从数据库中获取的对象?