1

I have multiple buttons on an HTML page. When a user clicks them, I want to call respective functions and manipulate the database.

I don't know if Django-forms are the right thing to use here. If yes, should I use different forms for different buttons?

1 Answer 1

3

Just map your view function to a url and call it, for example:

views.py

def remove_item(request, pk):
    item = Item.objects.get(pk=pk)
    item.delete()
    return redirect('home')

urls.py

urlpatterns = [
    path('remove_item/<int:pk>/', views.remove_item, name='remove_item'),
]

item.html

{{ item.name }}
<a href='{% url 'remove_item' item.pk %}'><button>Delete</button></a>

This is just an example function to delete an item that supposedly exists.

To answer your other question: Yes you can use forms with action attribute containing a url to the view that would handle its submittion (that usually means that form processes some sent data) and yes you can use multiple forms/buttons on the same page.

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

4 Comments

But I don't want to create separate URLs for every button.
Well you'll have to my friend, welcome to web-development :)
Are there any other methods? Like how facebook's like button work without redirecting to another URL?
Facebook is using React.js to display their API data on webpages, when you click the Like button the Post or a Picture it activates the endpoint in the API, component gets updated asynchronously and after that the data is being sent to the database, if you want to understand it better then you have to read up on React components and states but for now I recommend starting with Django documentation here: docs.djangoproject.com/en/3.1/intro/tutorial01

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.