Y
Y
Yura2021-08-10 15:50:35
Django
Yura, 2021-08-10 15:50:35

Why is the function from the button called without being pressed?

I want to make a button for deleting an object, I made such a button in the template

<button onclick="{% delete_post '{{i.pk}}' %}">Delete post</button>

In tags such a function
@register.simple_tag()
def delete_post(pk):
    try:
        post = Post.objects.get(pk=pk)
        post.delete()
    except:
        pass

But for some reason, the function is not called when the button is clicked, but simply when the page is loaded.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alternativshik, 2021-08-10
@alternativshik

Because you need to read the documentation first, and then write the code.

M
Max Rokitsky, 2021-08-11
@Exenzi

The tags are executed when the page is rendered. They are not made for this.
For such functionality, you need to make a view, register it in urls.py, specifying the name. And then specify this name through {%
url 'url name' i.pk %}.
And yes, javascript is called in onclick. Or make not a button, but a link that will call the view. Or write javascript that calls the view if you want to do it without reloading the page.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question