pythondjangodjango-formschoicefield

Django populate a form.ChoiceField field from a queryset and relate the choice back to the model object


I have a simple form:

class SubmissionQuickReplyForm(forms.Form):
    comment_text = forms.CharField(label='', required=False, widget=forms.Textarea(attrs={'rows':2}))

I want to add a form.ChoiceField to the form, where the options in the ChoiceField is populated from a queryset.

class SubmissionQuickReplyForm(forms.Form):
        comment_text = forms.CharField(label='', required=False, widget=forms.Textarea(attrs={'rows':2}))
        choice = forms.ChoiceField(...)

For example, if I have:

q = MyChoices.Objects.all()

How can I populate the ChoiceField with the contents of q, so that when I am handling the results of the form in my view, I can get the object back out at the end?

    if request.method == "POST":
        form = SubmissionQuickReplyForm(request.POST)
        if form.is_valid():
            ch = get_object_or_404(MyChoices, pk=?)
            # How do I get my object from the choice form field?

Solution

  • You can use ModelChoiceField instead.

    choice = forms.ModelChoiceField(queryset=MyChoices.objects.all())
    

    And you can get by simply call cleaned_data like this.

    if request.method == "POST":
        form = SubmissionQuickReplyForm(request.POST)
        if form.is_valid():
            ch = form.cleaned_data.get('choice')