0

I'm trying to implement a form of a single field in Django. The objective is to pass an integer variable (counter) to the views.py file. The template is completely custom, the value of the variable "counter" is shown in the screen while it can be increased/decreased using two buttons.

I can't manage to read this variable from my views.py file, and I have no idea what I am doing wrong. This is what I've done:

Template file:

<form method="POST" action="{% url 'animo' ejercicio=ejercicio %}">{% csrf_token %}

            <p class="mensaje">{{pregunta_valoracion}}</p>
            <div id="contadormin">

                <input type="button" id="number-change-button" value="-" onclick="subtract()"  name="counter"/>

                <div id="minutos">
                    <p id="counter">0 {{unidad}}</p>
                </div><script>
                    var i = 0;
                    var uni = {{unidad}};

                    function add() {

                    document.getElementById('counter').value = ++i;
                    document.getElementById('counter').innerHTML = i;
                    }
                    function subtract() {
                        if (i> 0){ 

                    document.getElementById('counter').value = --i;
                    document.getElementById('counter').innerHTML = i;
                        }
                    }
                </script>
                <input type="button" id="number-change-button" value="+" onclick="add()" name="counter" />
            </div>

            <input type="submit" class="save btn btn-default" value= "HECHO"</input>
        </form>

Views file:

if request.method == 'POST':

    veces = request.POST.get('counter', '')

Any ideas?

1 Answer 1

1

The only items with name="counter" in your template are the + and - buttons. You don't actually have a field containing the counter value itself, so there's no way it can be submitted in the form.

Remove the "counter" names from those buttons, and instead of putting the counter value in a <p> element, put it in an <input name="counter">.

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

2 Comments

Thanks Daniel, yes you're right, using the "input" field it works... but my template isn't the same anymore. I don't want to have a common input box on it, but a black screen with the value of "counter" and two buttons to increase/decrease its value (That's why I understand these are the "input" fields...). Isn't there any way to "read" the value of the counter without using an input box?
Then use a hidden input, and get your JS to update both the text and the input.

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.