【问题标题】:Django populate a form.ChoiceField field from a queryset and relate the choice back to the model objectDjango 从查询集中填充一个 form.ChoiceField 字段,并将选择与模型对象相关联
【发布时间】:2016-01-14 04:01:23
【问题描述】:

我有一个简单的表格:

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?

【问题讨论】:

    标签: django django-forms choicefield


    【解决方案1】:

    您可以改用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')
    

    【讨论】:

    • 应该是MyChoices.objects.all() - 小写的对象:)
    【解决方案2】:

    对于 ChoiceField,您可以使用

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

    【讨论】:

    • ^ 不要这样做——它只会在模块加载时进行评估,这意味着选择不会随着数据的变化而更新。
    • ChoiceField 没有 queryset ,所以这是一种填充choiceField @AdamBard 的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2022-10-16
    相关资源
    最近更新 更多