M
M
Mikhail Bolev2021-04-03 10:37:36
Django
Mikhail Bolev, 2021-04-03 10:37:36

How to get field value from form in django template?

Good afternoon. How to get data from template form field? The form is specified explicitly. I need to get two values: increment and decrement, and then process them in the view. I'll give you the code.

sample

<form action="{% url 'cart:cart_modificate' product.id %}" method="post">
     {% csrf_token %}
      <input type="hidden" name="product" value="{{product.id}}" />
      <input type="hidden" name="increment" value="increment" />
      <input type="submit" value="+" />
</form>
<form action="{% url 'cart:cart_modificate' product.id %}" method="post">
     {% csrf_token %}
      <input type="hidden" name="product" value="{{product.id}}" />
      <input type="hidden" name="decrement" value="decrement" />
      <input type="submit" value="-" />
</form>


show start
def cart_modificate(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    increment =


You can of course create two views for each form. But I want to get by with one.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2021-04-03
@Scorpion_MB

def cart_modificate(request, product_id):
    if request.method =='POST':
        increment = request.POST.get('increment')
        ... # для остальных полей по аналогии + добавить условие

But it can be easier:
<form action="{% url 'cart:cart_modificate' product.id %}" method="post">
     {% csrf_token %}
      <input type="submit" value="increment" />
      <input type="submit" value="decrement" />
</form>

def cart_modificate(request, product_id):
    if 'increment' in request.POST:
        # do something
    else:
        # do something else

D
Dimonchik, 2021-04-03
@dimonchik2013

https://tutorial.djangogirls.org/ru/django_forms/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question