Home > OS >  How to delete data from database with a button using only DJANGO python, java script, and HTML?
How to delete data from database with a button using only DJANGO python, java script, and HTML?

Time:07-23

I am working on a django project where my database gets populated from a post call, and for quality of life, I want to be able to clear ALL of the data from the database at the click of a button. If it's possible, I'd like to only use python, javascript, and HTML. I've done some searching on here and haven't found any question like this so far with an answer. Here's a link to a similar question with no answer. There is a question that is similar to mine, but OP is using PHP, jquery, and SQL, which isn't ideal for me. I haven't attempted any code because I don't know where to start. If anyone has knowledge about this kind of thing, it would be much appreciated if you gave me a starting place.

In regards to rendering my table, I am using the following html code:

<table id="mytable" border="1" cellpadding="2">
    <thead>
        <th>Src_Fname</th>
        <th>Dest_Fname</th>
        <th>Bytes_Xfer</th>
        <th>Xfer_Sec</th>
        <th>Xfer_MBPS</th>
    </thead>
    <tbody id="tablebody">
    {% for ftp in filetp %}
    <tr>
        <td>{{ ftp.Src_Fname }}</td>
        <td>{{ ftp.Dest_Fname }}</td>
        <td>{{ ftp.Bytes_Xfer }}</td>
        <td>{{ ftp.Xfer_Sec }}</td>
        <td>{{ ftp.Xfer_MBPS }}</td>
    </tr>
    {% endfor %}
    </tbody>
</table>

And here is the backend render definition in my views.py

def ftptable(request):
    filetp = FTP.objects.all()
    return render(request,'ftp.html',{'filetp':filetp})

My FTP object is just a class with all the variables from the HTML code set as char fields.

CodePudding user response:

For this, I would just make a POST request and pass a header called "button" with a name like "Delete All". Then in your view you can put something along the lines of if request.method == "POST" and button == "Delete All": to find when the button is hit. Somethin like:

In your template -

<script>
            $.ajax({
                    url: '//'   "/",
                    type: 'POST',
                    headers: {'X-CSRFtoken': '{{ csrf_token }}', 'button':'Delete_All'},
                    data: dict,
                    dataType: 'json'
                })
    </script>

You'll need to populate your URL here as I wasn't able to gleam it from your above code

Then, In your view -

if request.method == "POST":
            button = request.headers.get('Button')

            if button == "Delete_All":
                models = [list of all models here]
                for model in models:
                    model.objects.all().delete

This should work pretty well for just wiping everything in your database, it won't reset auto incrementing ids though. Don't know how the rest of your app is laid out so if you need more complete deletion of data just say so.

  • Related