1

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 %}
znawca
  • 279
  • 5
  • 15
  • 1
    You would need to create a link/button/some other element that when clicked calls that view function. Either by going to a specific URL or with AJAX. – kylieCatt May 27 '15 at 15:09

1 Answers1

3

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.

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
  • 4
    That souldn't be a link, but a form with method="POST" instead. Deleting (or modifying) data based on a GET is a bad practice (see http://stackoverflow.com/questions/705782/why-shouldnt-data-be-modified-on-an-http-get-request). – Weier May 27 '15 at 15:25
  • @Weier Update answer to use a form with the HTTP `DELETE` method – kylieCatt May 27 '15 at 15:31
  • 1
    I think you forgot to include `csrf_token`. – xyres May 27 '15 at 15:40
  • Thank You for advices, i added this what i have now in this template, what else must i write? – znawca May 27 '15 at 15:56
  • It's interesting that HTML5 doesn't support `DELETE` for forms. After a quick search I found an answer on [SE: Programmers](http://programmers.stackexchange.com/questions/114156/why-are-there-are-no-put-and-delete-methods-on-html-forms) that says HTML forms don't support `PUT` or `DELETE` basically because no on has written a spec for it. – kylieCatt May 27 '15 at 15:57
  • You need to have a URL defined in `urls.py` that will direct the request to the `delete_product()` function. Notice the string parameter of the `{%url%}` template tag amtches the `name` parameter of the URL. – kylieCatt May 27 '15 at 15:59