Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 462
43Tesseracts Avatar asked Jan 14 '16 04:01

43Tesseracts


2 Answers

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')
like image 136
Adiyat Mubarak Avatar answered Oct 17 '22 07:10

Adiyat Mubarak


For ChoiceField you can use

    choice = forms.ChoiceField(choices=[
    (choice.pk, choice) for choice in MyChoices.objects.all()])
like image 42
Dimitris Kougioumtzis Avatar answered Oct 17 '22 06:10

Dimitris Kougioumtzis