【问题标题】:Select a valid choice. x is not one of the available choices选择一个有效的选项。 x 不是可用的选择之一
【发布时间】:2017-10-25 13:30:02
【问题描述】:

我知道这个问题已经在 Stackoverflow 上被问过十几次了,但我都已经问过了,但它们并没有解决我的问题。通常,当模型字段为整数时,它们中的大多数与选择字符有关,反之亦然。但这是我的情况

我正在开发 Django 帮助台,这是一个基于 django 的开源票务平台,可以在这里找到:https://github.com/django-helpdesk/django-helpdesk

我已经对他们的 forms.py 进行了一些更改以提交公共票证,并且它一直在工作,直到我最近添加了一个新队列。

Forms.py

class PublicTicketForm(CustomFieldMixin, forms.Form):

    queue = forms.ChoiceField(
        widget=forms.Select(attrs={'class': 'form-control'}),
        label=_('Queue'),
        required=True,
        choices=()
    )

因此,此表单在调用时会在视图中填充选项

form = PublicTicketForm(initial=initial_data)
        form.fields['queue'].choices = [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] + \
                                       [('', 'Other')] #I'm thinking this line may be the problem here


    return render(request, 'helpdesk/public_homepage.html', {
        'form': form,
        'helpdesk_settings': helpdesk_settings,
    })

这是form.fields['queue'].choices 打印的内容:

[(6L, u'Account'), (7L, u'Support'), (4L, u'Orders'), (5L, u'Products'), (8L, u'Request'), (u'', u'Other')]

所以,每当我选择一个队列并提交时,表单将不会提交并且会抛出这个错误。

"Not one of the available choices"

据我所知,选择都是整数而不是字符。我在这里想念什么?我们将不胜感激所有帮助!

【问题讨论】:

  • 为什么ID打印为6L7L等? L 是什么意思? Queue.id是什么类型?
  • 我认为 L 表示长整数类型。当我执行type(q.id) 时,它会显示Long
  • 您使用 Python 2 有什么特别的原因吗? FWIW,在 Python 3 中,intlong 已统一为改进的 int 类型。
  • 其实没有理由,我们还没来得及迁移到 Python3
  • 请显示整个视图。

标签: python django forms


【解决方案1】:

我的猜测是您正在为 GET 请求设置选项,而不是在验证表单数据时为 POST 请求设置选项。您可以通过将设置选项的代码移动到表单的__init__ 方法中来避免此问题。自己。

class PublicTicketForm(CustomFieldMixin, forms.Form):

    queue = forms.ChoiceField(
        widget=forms.Select(attrs={'class': 'form-control'}),
        label=_('Queue'),
        required=True,
        choices=()
    )

    def __init__(self, *args, **kwargs):
        super(PublicTicketForm, self).__init__(*args, **kwargs)
        self.fields['queue'].choices = [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] + [('', 'Other')]

请注意,使用ModelChoiceField 可能更简单:

class PublicTicketForm(CustomFieldMixin, forms.Form):
    queue = forms.ModelChoiceField(queryset=Queue.objects.filter(...))

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 2021-01-25
    • 1970-01-01
    • 2018-06-11
    • 2021-04-12
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多