znawca
znawca

Reputation: 279

How to delete object in django view?

I have a model Product:

class Product(models.Model):
    name = models.CharField(verbose_name="name", max_length=40)
    cost = models.FloatField(verbose_name="price")

    def __unicode__(self):
        return self.name

I created a view where i can add new products but how can i delete these products?

my idea:

def delete_product(request, pk):
    if request.method == "POST":
        if form.is_valid():
            product = form.delete(commit=False)
            product.delete()
            return redirect('homeshop.views.product_list', pk=product.pk)

But what next? I added to template (where i can edit product and save it) but it does not work:

{{ delete_product }}

Now in my template:

{% block content %}
    <h1>Nowy wydatek</h1>
    <form method="POST" class="product-form">{% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>
{% endblock %}

Upvotes: 1

Views: 3458

Answers (1)

kylieCatt
kylieCatt

Reputation: 11049

You would need to do something like this:

template.html

{% for product in products %}
{% csrf_token %}
...
<form action="{% url 'delete_product' product.id %}" method="POST">
  <button type="submit">Delete</button>
</form>
...
{% endfor %}

then you would need to update your urls.py to have a URL defined that calls your delete function when the proper URL is visited.

    url(
        r'^delete/<product_id>$',
        'delete_product',
        name='delete_product'
    )

I don't know exactly how your urls.py is laid out so your URL may have to look a little different.

Upvotes: 3

Related Questions