[Django]-Django form dropdown list of numbers

61👍

You’re looking for a ChoiceField which renders as a select html element by default.
https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield

class CronForm(forms.Form):
    days = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)])

0👍

you can start by choosing to render the fields manualy.
A simple example:-

{% for field in form %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }} {{ field }}
            {% if field.help_text %}
                <p class="help">{{ field.help_text|safe }}</p>
            {% endif %}
        </div>
    {% endfor %}

This will render the form without any styling then you have to apply the relevent class to create a drop down list(copied from w3c dropdown css):-

 <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials
    <span class="caret"></span></button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">HTML</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">CSS</a></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">JavaScript</a></li>
      <li role="presentation" class="divider"></li>
      <li role="presentation"><a role="menuitem" tabindex="-1" href="#">About Us</a></li>
    </ul>
  </div>
</div>

combining the two :-

<div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Days
            <span class="caret"></span></button>
        <div class="fieldWrapper">
            <ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
                {% for field in form %}
                    <li class="fieldWrapper">
                        {{ field.errors }}
                        {{ field.label_tag }} {{ field }}
                        {% if field.help_text %}
                            <p class="help">{{ field.help_text|safe }}</p>
                        {% endif %}
                    </li>
                {% endfor %}
            </ul>
        </div>
    </div>

Leave a comment