0

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!

1 Answer 1

2

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 }}">
    Delete
</button>

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

If I could upvote you 10000 times I definately would! Now whenever I click DeleteButton I receive 'GET' request with value of current button clicked! Works just perfect. Now I need to just write something like this: if (request.GET.get('DeleteButton')): Next question: after GET request I'm deleting object and rendering page again. But this GET request is still in my page address. How can I force reset page address after clicking DeleteButton? Note.objects.filter(id = request.GET.get('DeleteButton')).delete()
UPDT: Figured out.I just use if (request.GET.get('DeleteButton')): Note.objects.filter(id = request.GET.get('DeleteButton')).delete() return redirect('/notes/')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.