Delete data from a model in Django

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

urls.py

Open your 'urls.py' file in the project folder. We will need to add a path to those currently on the 'urlpatterns', so add the path:

path('product/<int:prodID>/delete', myapp_views.deleteproduct, name='deleteproduct'),

This is similar to the 'showproduct' path, but with the delete section on the end.

views.py

Now open the 'views.py' in your app folder. Add a new subroutine for the delete feature called 'deleteproduct', the code below is a starting point for the subroutine:

def deleteproduct(request, prodID):
    if request.user.is_superuser:

    else:
        return redirect('/product/'+str(prodID))

This subroutine passes the 'request' and the 'prodID'. The if statement is to check if the user is a superuser, maybe only a superuser can delete a product. If they aren't a superuser they will be redirected back to the single product page for this product.

Now we need to check if the 'delete' button and 'confirm' checkbox have been ticked, so update the code above so it includes:

def deleteproduct(request, prodID):
    if request.user.is_superuser:
        if 'delete' and 'confirm' in request.POST:
            Product.objects.filter(pk=prodID).delete()
            return redirect('products')
        return render (request, 'MyApp/deleteproduct.html')
    else:
        return redirect('/product/'+str(prodID))

template

In the templates folder for your app, create the following:

{% extends "MyApp/base.html" %}

{% block title %}Delete Product{% endblock %}

{% block content %}

		<form method="POST">
			{% csrf_token %}
			<p>Tick to Confirm Deletion: <input type="checkbox" name="confirm"></p>
			<button type=submit name=delete> Delete</button>
		</form>
	
{% endblock %}

Save this as 'deleteproduct.html'.

testing

At the moment you should be able to visit a product page, eg '/product/1'. Make sure you login as the superuser, If you add '/delete' onto the address you should get the confirmation form to delete the product. If the user isn't the superuser it should redirect back to the single product page.