Home > other >  Django/Python - remove row in sqlite3 database with form button
Django/Python - remove row in sqlite3 database with form button

Time:03-10

I want to have a delete button to delete a row in my sqlite3 database. I'm almost there but I'm not sure what I should add to send the ID from my html of the row to my views.py. This is what I have:

mailindex.html

<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
    <div >
        <a href="{% url 'core:mail' mail.id %}" >Manage</a>
        <button type="submit" name="deletemail" value="deletemail" >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)

It works, in a sense that when I push the delete button it deletes email with ID = 13. Which is logical as I put no. 13 there. I would like to replace '13' with the mail.id, but I'm not sure how to do this. I hope it is possible: I would prefer it to be as simple as possible, so to not create an extra url, but again don't know if this is possible...

CodePudding user response:

Use deletemail tag in type:hidden another input not button.

CodePudding user response:

Try this

<div >
    <a href="{% url 'core:mail' mail.id %}" >Manage</a>
    <input type="hidden" name="deletemail" value="13">
    <button type="submit" >Delete</button>
</div>
  • Related