Disciples Disciples - 1 year ago 125
Python Question

How to delete models using button and GET request in Django?

Here's the problem: in my rendered html-page I have multiple what I call 'thumbnails' of text data aka Notes (Note is my Model in Django). I decided it would be good idea to bind button "Delete" to every thumbnail: User clicks "Delete" on some Note —> it's get deleted.
What I've come to (in my views.py):

ids=[x.id for x in Note.objects.all()]
buttons = []
for x in ids:
buttons.append('DeleteButton' + str(x))
if (request.GET.get(x for x in buttons)):
print("Button click registered @ ", x)

Well, It doesn't actually register any button clicks and thus not printing "click registered". My button looks like this in notes.html:

<input type="submit" class="btn btn-default" value= "DeleteButton" name="DeleteButton{{ Note.id }}">

Any ideas how can I actually register any buttons clicked? Thanks in advance!

Answer Source

request.GET.get(x for x in buttons) doesn't do what you think at all. It tries to get a single parameter, consisting of a list of all the button names. That can never work.

But this is a very inefficient way of doing things anyway. Rather than iterating over every ID and seeing if it's in the GET, you should just find the things that are in the GET and extract their IDs. Something like:

button_ids = []
for item in request.GET:
    if item.startswith('DeleteButton'):
        button_ids.append(item.replace('DeleteButton', ''))
notes = Note.objects.filter(id__in=button_ids)

An even better way would be to use the actual button tag rather than input, which allows you to split the value from what is displayed in the button. Then you can just use a single name with different values.

<button name="DeleteButton" value="{{ note.id }}">

Now you can simply do:

button_ids = request.GET.getlist('DeleteButton')

(Note that IE versions before 8 had various bugs with the button element, so if you need to support these this isn't a good idea.)