'How to call view function via button from template in Django?
I've searched some of the related questions and I couldn't figure out how to do it. That is why I am posting a new question here.
I have a base.html file and there is a button which should run a function from views.py file. Here is the button code:
<form role="form" action="" method="POST">
{% csrf_token %}
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
And here is my function from views.py file:
def create_new_product(request):
if request.method == 'POST':
'''Execute the code here'''
return render (request, 'products/base.html')
And in my Products' urls.py file:
app_name = 'products'
urlpatterns = [
path('create-new-product/', views.create_new_product),
path('', views.IndexView.as_view(), name='base'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
]
Normally I have an IndexView class in views.py file which lists all the current products and what I expect from the above function is that it will generate new products and new products will also be listed in 'products' page.
The above function is not inside the IndexView class by the way.
Solution 1:[1]
You will stay on the same page with action="#"
Try instead action="" so you will stay on the same page but reloaded.
Update:
Read your comment.
The name argument is useful to call your url in Django template like :
path('create-new-product/', views.create_new_product, name='create_new_product')
The app_name = 'products' is very important. It tells Django where to check your path. So you can call your view everywhere in your project by:
<a href="{% url 'products:create_new_product' %}">...</a>
<form action="{% url 'products:create_new_product' %}">...</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
