pythondjangojsgrid

How to delete object in django?


enter image description here

@csrf_exempt
def ajax_owner_delete(request, pk):
    product = Product.objects.get(pk=pk)
    product.delete()
    return HttpResponse(status=200)


class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products', null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, db_index=True, null=True)
    slug = models.SlugField(max_length=200, db_index=True, null=True)
    sell_price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
    prime_cost = models.DecimalField(max_digits=10, decimal_places=0, null=True)
    usd_price = models.DecimalField(max_digits=10, decimal_places=0, null=True)
    stock = models.PositiveIntegerField(verbose_name='stock', null=True)
    created = models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_detail',
                       args=[self.id, self.slug])

I am doing this, it deletes every field of a model, but object still exists(look at the image)


Solution

  • Try this:

     def ajax_owner_delete(request, pk):
        product = Product.objects.get(id=pk)
        product.delete()
        return HttpResponse(status=200)