Django 从查询集中填充一个 form.ChoiceField 字段并将选择关联回模型对象

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

我有一个简单的表格:

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

我想向表单添加一个 form.ChoiceField,其中 ChoiceField 中的选项是从查询集中填充的。

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

例如,如果我有:

q = MyChoices.Objects.all()

如何用 q 的内容填充 ChoiceField,以便当我在我的视图中处理表单的结果时,我可以在最后取回对象?

    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?

您可以改用ModelChoiceField

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

你可以像这样简单地调用cleaned_data

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

对于 ChoiceField,您可以使用

    choice = forms.ChoiceField(choices=[
    (choice.pk, choice) for choice in MyChoices.objects.all()])