Search code examples
djangodjango-formsdjango-templatesdjango-viewshidden-field

How can I populate value of a hidden field in Django from the value of a range slider


So I am building an app that users are able to use a range slider to update a database with a new integer value. I have the slider which provides me with the integer value that I would like to return to the view, but I don't know how to return this value from the template.

https://docs.djangoproject.com/en/3.0/ref/forms/widgets/

I looked at the documentation but I couldn't find anything regarding range inputs.

# forms.py

from django import forms

class UpdateForm(forms.Form):
    update = forms.IntegerField(widget=forms.HiddenInput(**something like:value='slider-input**}}))
# views.py
def home_view(request):
    form = UpdateForm()
    return render(request, 'main/index.html', {'form': form})
# index.html
...
    <form id="update-form" method="post">
        {% csrf_token %}
        {{ form }}
        <div id="slider">
            <input class="slider-widget" min="0" max="25" step="1" value="0" type="range">
        </div>

        <div class="options">
            <a href="{% url 'main-home' %}">
                <img src="{% static 'main/media/cancel.png' %}" alt="cancel">
            </a>
            <button type="submit">
                <img src="{% static 'main/media/confirm.png' %}" alt="confirm">                
            </button>
        </div>        
    </form>
...

Solution

  • In it's simplest form you can take the slider value directly and do not need a HiddenField.

    Your simple form

    class UpdateForm(forms.Form):
        update = forms.IntegerField()
    

    In your html template just make sure that you add the 'name' attribute to your slider and give it the same name as the field name in your form:

    <div id="slider">
         <input name="update" class="slider-widget" min="0" max="25" step="1" value="0" type="range">
    </div>
    

    and in your view just process the form:

    form = UpdateForm(request.GET or None)
    if form.is_valid():
        slider_value = form.cleaned_data['update']
        # do somthing
    

    Actually you do not really need a form for a simple case like this. You can also fetch the value directly in your view

    slider_value = request.GET.get('update')