#14769: Voting example from tutorial - use of forms API - suggestion ---------------------------+------------------------------------------------ Reporter: bradders | Owner: nobody Status: new | Milestone: Component: Documentation | Version: 1.2 Keywords: | Stage: Unreviewed Has_patch: 0 | ---------------------------+------------------------------------------------ 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> }}} -- Ticket URL: <http://code.djangoproject.com/ticket/14769> Django <http://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To post to this group, send email to django-upda...@googlegroups.com. To unsubscribe from this group, send email to django-updates+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-updates?hl=en.