Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

python - Django form multiple choice

I am a newbie in Django and I would really appreciate it if you could offer me some guidance. I am trying to create a form that allows a user to tick one or more options. I understood that I must use MultipleChoiceField field with a CheckboxSelectMultiple widget but the Django documentation doesn't offer an example on this topic. I would be grateful if you could offer me an example and explain how do I handle the results. For example if I have a form with the options a b c d, and the user ticks c and d. Also how do I specify the choices(I don't want to use a db, a list of strings is what I have in mind)? Thanks a lot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

forms.py

class SomeForm(forms.Form):
    CHOICES = (('a','a'),
               ('b','b'),
               ('c','c'),
               ('d','d'),)
    picked = forms.MultipleChoiceField(choices=CHOICES, widget=forms.CheckboxSelectMultiple())

views.py

def some_view(request):
    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
            picked = form.cleaned_data.get('picked')
            # do something with your results
    else:
        form = SomeForm

    return render_to_response('some_template.html', {'form':form },
        context_instance=RequestContext(request))

some_template.html

<form method='post'>
    {{ form.as_p }}
    <input type='submit' value='submit'>
</form>

results:

checkboxselectmultiple

explanation:

choices:

The first element in each tuple is the actual value to be stored. The second element is the human-readable name for the option.

getting selected boxes:

form.cleaned_data.get('picked') will result in a list of the 'actual values'. For example, if I replaced the # do something with your results with print picked you see:

[u'a', u'c']

in your console


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...