Home > Mobile >  Deleting an Item from the cart on Django not working
Deleting an Item from the cart on Django not working

Time:06-02

My "Remove" button to remove an item from cart is not working. My views.py file:

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'))

My cart.html file:

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

When I press the remove button it won't delete. I don't know why it is happening. whats wrong? Do I have to change in views or in my html file?

UPD:

My course model:

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

My cart and course models are added.

CodePudding user response:

You should access hidden field through name and then get instance and remove it in the following way:

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"  value="Remove">
</form>

urls.py


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

  • Related