Django Forms

33 views
Skip to first unread message

test

unread,
Oct 21, 2017, 6:29:00 PM10/21/17
to Django users
Hi,

I have a form that contains a question and a multiple choice answer field. 

For example:
What is your favorite color?
  • Blue
  • Green
  • Red
  • Yellow
I render the page with a list of forms (or I guess formset?) and loop through them. So something like this.

<form>
for form in formset:
 form

<submit button>
</form>


Since each form is set to only allow you to select 1 multiple choice option, if I add many forms in one page, I can only select one option overall. So if I answer question 1, I can't answer any of the other questions without it unselecting question 1's answer.

Does anyone know how to fix this?

James Schneider

unread,
Oct 21, 2017, 6:41:16 PM10/21/17
to django...@googlegroups.com



Since each form is set to only allow you to select 1 multiple choice option, if I add many forms in one page, I can only select one option overall. So if I answer question 1, I can't answer any of the other questions without it unselecting question 1's answer.

Does anyone know how to fix this?

If that's the case you are not formatting the form correctly. Each form set should contain it's own radio group of answers so that an answer may be selected for each one. Post up the template code you're using.

-James

test

unread,
Oct 21, 2017, 7:45:02 PM10/21/17
to Django users


class PollForm(forms.Form):
    answer = forms.ChoiceField(
        widget=forms.RadioSelect,
        choices=cool_choices)

    def __init__(self, poll, *args, **kwargs):
        super(PollForm, self).__init__(*args, **kwargs)
        b = poll.choice_set.all()
        list_choice = []
        for i in range(len(b)):
            list_choice.append(b[i].choice)

        list_choice = zip(list_choice, list_choice)
        self.fields['answer'].choices = list_choice
        self.fields['answer'].label = poll.question

        self.fields[poll.pk] = self.fields['answer']
        del self.fields['answer']


So I managed to fix it by creating a name tag for each of the radioselect options. I thought self.fields['answers'].widget.name would let me set the tag but that did not work as there was no default name tag. So I googled and I found that the last two lines made it work
        self.fields[poll.pk] = self.fields['answer']
        del self.fields['answer']
It set the name tag as the pk for the poll. I honestly don't understand how that works. Could you please explain how the last two lines work?
Reply all
Reply to author
Forward
0 new messages