Django populate a form.ChoiceField field from a qu

2020-06-04 06:24发布

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?

2条回答
男人必须洒脱
2楼-- · 2020-06-04 07:01

For ChoiceField you can use

    choice = forms.ChoiceField(choices=[
    (choice.pk, choice) for choice in MyChoices.objects.all()])
查看更多
一夜七次
3楼-- · 2020-06-04 07:08

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')
查看更多
登录 后发表回答