从 Django 上的购物车中删除一个项目不起作用

Deleting an Item from the cart on Django not working

我用于从购物车中删除商品的“删除”按钮不起作用。 我的 views.py 文件:

from urllib.request import Request
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse_lazy
from django.views.decorators.http import require_POST
from requests import request

from courses.models import Course
from udemy.models import Enroll
from .cart import Cart


@require_POST
def cart_add(request, slug):
    cart = Cart(request)  # create a new cart object passing it the request object
    course = get_object_or_404(Course, slug=slug)
    cart.add(course=course, quantity=1, update_quantity=False)
    return redirect('cart:cart_detail')


def cart_remove(request, slug):
    cart = Cart(request)
    course = get_object_or_404(Course, slug=slug)
    cart.remove(course)
    return redirect('cart:cart_detail')


def cart_detail(request):
    cart = Cart(request)
    return render(request, 'cart/detail.html', {'cart': cart})


@login_required(login_url='/login')
def cart_checkout(request):
    carts = Cart(request)
    for cart in carts:
        course = cart['course']
        # course = get_object_or_404(Course, slug=course.slug)
        Enroll.objects.create(course=course, user_id=request.user.id)
    messages.success(request, 'Successfully checked out!')
    carts.clear()
    return redirect(reverse_lazy('cart:cart_detail'))

我的 cart.html 文件:

<div class="move-remove">
<div>
<form action="" method="post">
{% csrf_token %}
<input type="hidden" value="{{ course.slug }}">
<input type="submit" class="btn-success"                                              value="Remove",name="Remove">
</form>
</div>

当我按下删除按钮时,它不会删除。我不知道为什么会这样。怎么了?我是否必须更改视图或我的 html 文件?

更新:

我的课程模型:

from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.utils.text import slugify
from django.utils.timezone import now

from accounts.models import User


class Category(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=200, unique=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Category, self).save(*args, **kwargs)


class Course(models.Model):
    title = models.CharField(max_length=200)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    slug = models.SlugField(max_length=200, unique=True, primary_key=True, auto_created=False)
    short_description = models.TextField(blank=False, max_length=60)
    description = models.TextField(blank=False)
    outcome = models.CharField(max_length=200)
    requirements = models.CharField(max_length=200)
    language = models.CharField(max_length=200)
    price = models.FloatField(validators=[MinValueValidator(9.99)])
    level = models.CharField(max_length=20)
    thumbnail = models.ImageField(upload_to='thumbnails/')
    video_url = models.CharField(max_length=100)
    is_published = models.BooleanField(default=True)
    created_at = models.DateTimeField(default=now)
    updated_at = models.DateTimeField(default=now)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Course, self).save(*args, **kwargs)


class Lesson(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='lessons')
    title = models.CharField(max_length=100)
    duration = models.FloatField(validators=[MinValueValidator(0.30), MaxValueValidator(30.00)])
    video_url = models.CharField(max_length=100)
    created_at = models.DateTimeField(default=now)
    updated_at = models.DateTimeField(default=now)

    def __str__(self):
        return self.title

我的购物车和课程模型已添加。

您应该通过name访问隐藏字段,然后通过以下方式获取实例并删除它:

views.py

def cart_remove(request):
    cart = Cart(request)
    course = get_object_or_404(Course, slug=request.POST.get('my_slug'))
    cart.remove(course)
    return redirect('cart:cart_detail')

cart/detail.html

<form action="{% url 'cart:cart_remove' %}" method="POST">
    {% csrf_token %}
    <input type="hidden" value="{{course.slug}}" name='my_slug'> 
    <input type="submit" class="btn-success" value="Remove">
</form>

urls.py


urlpatterns = [
    path('remove/', views.cart_remove, name='cart_remove')
]