Home > OS >  Why does request.POST always contains name of the button? How to avoid it?
Why does request.POST always contains name of the button? How to avoid it?

Time:12-17

This is my HTML code:

<!DOCTYPE html> <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        {% load static %}
        <script src="{% static 'jquery-3.6.2.min.js' %}" ></script>
        <script src="{% static 'jquery.js' %}" ></script>
    </head>



    <body>
        <form action="{% url 'index' %}" method="post">
            {% csrf_token %}
            <button name="button1">button1</button>
            <button name="button2">button2</button>
            <input type="text" name="textbox">
        </form>
    </body>

</html>

Every time I type some text in the textbox, let's say I type: "hi" and hit enter, the request.POST returns:

<QueryDict: {'csrfmiddlewaretoken': ['FX1qFNzbQUX3fYzAwW27cOu83omLzifnlLU5X0WXXVdOiyNretM5b3VgsGy1OogA'], 'button1': [''], 'textbox': ['hi']}>

Why does request.POST contain 'button1': [''] even though I haven't clicked on it?

Is there a way to avoid request.POST to have 'button1': ['']?

CodePudding user response:

Remove a name attribute from your <button> tag if you don't need to know which buttons is pressed by a user:

<form action="{% url 'index' %}" method="post">
  {% csrf_token %}
  <button>button1</button>
  <button>button2</button>
</form>

As the button is an input as well and can contain name and value.


Alternatively you may use the feature to implement the following approach if you wish to vary your backend logic dependant of which button is pressed:

In a template file:

<form action="{% url 'index' %}" method="post">
  {% csrf_token %}
  <button name="action" value="button1_pressed">button1</button>
  <button name="action" value="button2_pressed">button2</button>
</form>

In your views.py:

if request.method == "POST":
    back = reverse('index')
    action = request.POST.get("action")

    if action == "button1_pressed":
        # do something
        messages.success(request, "Successed!")
        return redirect(back)

    if action == "button2_pressed":
        # do something else
        messages.success(request, "Successed!")
        return redirect(back)

CodePudding user response:

you may Try

<!--base.html--> 
{% load static %}

<!DOCTYPE html> <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="{% static 'jquery-3.6.2.min.js' %}" ></script>
        <script src="{% static 'jquery.js' %}" ></script>
    </head>



    <body>
{% block content %}
        <form action="{% url 'index' %}" method="post">
            {% csrf_token %}
           <input type="text" name="textbox">
            <button name="button1">button1</button>
            <button name="button2">button2</button>
 
        </form>

{% endblock %}
    </body>

</html>
  • Related