﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
14769	Voting example from tutorial - use of forms API - suggestion	bradders	nobody	"I'm a django newbie working through the tutorials and documentation to get me going for a project.

I built the simple Poll app - very useful introduction. I then wanted to learn the Forms API, and it seemed an obvious learning exercise to implement the voting form using the API. Turned out to be much harder than I expected - perhaps I haven't used the most appropriate technique - but can I suggest you include an implementation (happy for you to use mine) within the ""working with forms"" introduction to keep people like me sane.

My solution is below. I was using Google App Engine so you'll see use of object keys instead of ids and other limitations of app engine that I'm sure you could easily turn into proper django.

Implement a forms.VotingForm class:

{{{
class VotingForm(forms.Form):
    # this needs to be hidden    
    poll_key = forms.CharField(widget=forms.HiddenInput)
    
    # we need to add this choice dynamically at run time
    def __init__(self, vote_choices, *args, **kwargs):
        super(VotingForm, self).__init__(*args, **kwargs)
        
        form_vote_choices = []
        for vote_choice in vote_choices:
            form_vote_choices.append((vote_choice.key(),vote_choice.choice))  
    
        self.fields['choice']= forms.ChoiceField(label='Your vote',
                                   widget=forms.RadioSelect,
                                   choices=form_vote_choices)       
}}}
Change the poll.views.poll_detail function to populate the form:

{{{
def poll_detail(request, poll_key):
    
    aPoll = Poll.get(poll_key)
    aVotingForm = VotingForm(aPoll.choice_set)
    if aPoll:
        
        return render_to_response('polls/poll_detail.html',
            {'poll':aPoll,'voting_form':aVotingForm})
    else:
     
        raise Http404
}}}
And the html:
{{{
<form action=""/polls/{{ poll.key }}/vote/"" method=""post"">

{{ voting_form.as_p }}
<input type=""submit"" value=""Vote"" />

</form>
}}}"	New feature	closed	Documentation	1.2	Normal	needsinfo			Accepted	0	0	0	0	0	0
