Skip to content

Delete Storage

In this video, we are going to learn about generic Delete View.

In this video, we are going to write a Delete View api for Storage model.

Resources:

View

At first, open your views.py file of Center and create a Storage Delete class.

class StorageDelete(generic.DeleteView):

This class will inherit generic.DeleteView.

In this class, at first, we need to specify the model for which we are performing Delete Operation.

model = Storage

Now, lets specify the template_name for this view.

template_name = "storage/storage-delete.html"

After that, create a template named "storage-delete" in the templates/storage folder.

Template

Now, you have to download storage-delete.html file from the resources section. Download it and copy its content in this file.

{% extends 'mysite/base.html' %} 

{% block title %} 
    <title>Delete Storage</title>
{% endblock title %} 

{% block content %}
<div class="m-2 p-2">
    <h4>Are you sure you want to delete "{{ object }}" ?</h4>
    {% include "components/form.html" with form_name="Delete Storage" %}
</div>
{% endblock content %}

URL

Now, we need to specify the success url so that when django completes the delete operation, django will redirect the user to a certain page.

    def get_success_url(self):
        # We will redirect the user to storage list page once the delete process is completed.
        return reverse("center:storage-list", kwargs={"center_id": self.get_object().center.id})

After write the Storage Delete view, we need to setup path for this view. So, lets add path in the urlpatterns.

path("storage/delete/<int:pk>/", views.StorageDelete.as_view(), name="storage-delete"),

Using this primary key, django will know the instance of storage which you want to delete.

<a href="{% url 'center:storage-delete' object.id %}">
    <i class="fas fa-trash"></i> Delete Storage
</a>

[Run the development server and see the changes.]

In this way, we have learnt how to perform delete operation using generic DeleteView for any given model.

Git

Now add the changes to the staging area.

git add .

After that, commit the changes.

git commit -m "Added Storage CRUD Views"

Then push the changes to the remote repository.

git push origin main

[Commit the changes and push it in the remote repository.]