Django - button to remove row in sqlite3

Viewed 120

I have a question.. I got a Django Application with a mailbox that shows a list with all the mails and their importance (priority to answer). clicking the button "Manage" goes to a view of a mail message.

Now I also want to add a "delete" button that will delete this email in the list aka the row from the sqlite3 database.

I have tried multiple things, because I saw this on multiple forums. My problem is that I'm quite new to Django and I don't know which answers I can combine with what I already have in my code.

This is what I have now (it doesn't work as I'm still trying to find working solutions)

mailindex.html:

<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
    <div class="form-group">
        <a href="{% url 'core:mail' mail.id %}" class="btn btn-secondary btn-sm">Manage</a>
        <button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button>
    </div>
</form>

views.py

class MailboxView(generic.ListView):
    extra_context = {"mailbox_page": "active"}
    model = MailMessage
    context_object_name = 'mails'
    template_name = 'core/mailbox/mailindex.html'

    def post(self, request):
        # if 'deletemail' in self.request.POST:
        if request.POST.get('deletemail'):
            mail = MailMessage.objects.get(pk=13)
            mail.delete()
            return HttpResponseRedirect(self.request.path_info)

EDIT: I am a bit further: it now works that the button deletes email with ID 13... How can I send the mail.id to my function in views.py?

1 Answers

Django will not trigger the delete_mail_listing, or any other method except the ones that are in the code flow of the ListView.

Probably the most elegant way to do this is working with a DeleteView:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import DeleteView

class MailMessageDeleteView(LoginRequired, DeleteView):
    model = MailMessage
    success_url = reverse_lazy('mailbox')

In the urls.py, you can then register this view:

urlpatterns = [
    path('', login_required(views.IndexView.as_view()), name='index'),
    path('mailbox', login_required(views.MailboxView.as_view()), name='mailbox'),
    path('mailbox/delete/<int:pk>/', views.MailMessageDeleteView.as_view(), name='delete')
]

and in the template you then submit to the MailMessageDeleteView:

<form  method="POST" action="{% url 'delete' pk=mail.pk %}">
    {% csrf_token %}
    <button type="submit" class="btn btn-secondary btn-sm">Delete</button>
</form>

Note: You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc].

Related