简体   繁体   中英

Django Form ChoiceField not working for 1 element lists

I discovered a weird instance while working on a Django web app.

I have a list of options that I would like users to select from a drop down list. To accomplish this I used the ChoiceField from Django forms. However, when my options contain only a single 2-tuple (eg. (("1", "one")) is invalid) nothing is displayed and I get the error "not enough values to unpack (expected 2, got 1) at line builds.as_p" in index.html. Once I add at least one more 2-tuple (eg. (("1", "one"), ("2", "two")) is valid) to my options this is fixed. What could be causing this?

forms.py

class BuildForm(forms.Form):
    OPTIONS = (("1", "One"), ("2", "two"))
    Build_IDs = forms.ChoiceField(choices=OPTIONS) 

views.py

from .forms import BuildForm

def index(request):
    builds = BuildForm()
    return render(request, 'ReportGenerator/index.html', {"builds":builds})

templates/App/index.html

{% if builds %}
     <h2>Pick a Build</h2>
     <form method="POST" class="build-form">{% csrf_token %}
       {{ builds.as_p }}
     </form>
{% else %}
    <p>No reports are available.</p>
{% endif %}

You're using wrong tuple syntax.

(("1", "one")) is not valid, (("1", "one"), ) (note the comma) however is. This comma is needed to avoid ambiguouty. For example, when you do 1 + (1) , without comma (1) could be a tuple or just 1 inside parentheses. Comma solves this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM