Deleting a listing#

Again we follow the same pattern as before. Url, view, and template.

Add the URL#

path('delete_listing/<delete_id>/', views.delete_listing, name='delete_listing')

Add the view#

Very similar to the edit view.

def delete_listing(request, delete_id):
    listing = Listings.objects.get(id=delete_id)
    if request.method == 'POST':
        listing.delete()
        return redirect('listings:my_listings')
    context = {'listing': listing}
    return render(request, 'listings/delete_listing.html', context)

Here were are calling the delete() function as opposed to the save() as in previous examples.

Add the template#

The key form element is:

<form method="POST">
        <div class="container">
        <!-- Security token by Django -->
        {% csrf_token %}
        <h3>Do you want to delete <b>{{listing.title}}</b> listing ? </h3>
        <p><input type="submit" class="btn" value="Delete" />
        <a class= "btn" href="{% url 'listings:my_listings'%}">Cancel</a></p>
    </div>
</form>

Note again, the use of the CSFR token.

Wire up the delete button#

Finally the href of the delete button on the my_listings template is wired up.

<a class="btn" href="{% url 'listings:delete_listing' my_listing.id %}">Delete</a>

So far, items can be listed, added, edited, and deleted. Full CRUD up and running.

So far this Educative learning path is paying dividends.