pythonjquerydjangoformsdjango-views

How to get a hidden input field value in a Django view?


I am working on a django application. In the application, I have a drop-down button in a form. There also is a hidden input field that will hold the value of the drop-down item selected. (I achieved this with jQuery). I want to access the value of the hidden field in the views.py file.

Right now when the form is submitted, I am only getting a None value returned. I am not sure what I am doing wrong. This is my code so far

HTML template

<form method="post" action="{% url 'test_app:get_data' %}">
    {% csrf_token %}
    <div class="dropdown">
        <button class="btn btn-primary btn-lg btn-block dropdown-toggle fruit-btn" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Fruit
        </button>
        <input type="hidden" name="fruit-name" id="fruit-name" value="" disabled>
        <div class="dropdown-menu">
            <ul class="list-group" role="menu" aria-labelledby="dropdownMenu">
                <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Apple</a></li>
                <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Banana</a></li>
                <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Mango</a></li>
            </ul>
        </div>
    </div>

    ...

    <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button>
</form>

views.py

def test_data(request):
    if request.method == 'POST':
        fruit = request.POST.get('fruit-name')
        print(fruit)

        return redirect("test_app:root")

    return render(request, 'test_app/root.html')

jquery code to get the value of the button in the hidden input field

$(document).ready(function() {
  $('.dropdown-item').click(function() {
    $('.fruit-btn').text($(this).text());
    $('.fruit-btn').val($(this).text());
    $('#fruit-name').val($(this).text());
    console.log($('#fruit-name').val())
  })
})

This is the output of the jquery console.log when I click a particular fruit

Mango

This is the output of the python print(fruit) from views.py when I submit the form

None

I am not sure what I am doing wrong. Any suggestions?


Solution

  • Remove the disabled attribute on the hidden field. After that, you should be able to get the value in your views.