我正在制作一个 Django 表单并使用 ChoiceField 生成一个带有不同选项的 <select> 框。我希望 <select> 框的第一个选项是“请选择:”,如果用户没有选择就提交表单,他会得到一个错误。

这样做的好方法是什么?

最佳答案

似乎 Django 没有对此类请求的内置支持。您可以通过继承 ChoiceField 并使其接受 blank_choice 参数来实现它。例如

from django import forms


class ChoiceField(forms.ChoiceField):
    def __init__(self, *args, **kwargs):
        self.blank_choice = kwargs.pop('blank_choice', None)
        super(ChoiceField, self).__init__(*args, **kwargs)

    def _get_choices(self):
        return self._choices

    def _set_choices(self, value):
        choices = list(value)
        if self.blank_choice:
            choices = [('', self.blank_choice)] + choices
        self._choices = self.widget.choices = choices

    choices = property(_get_choices, _set_choices)

这个空白选项被添加到正常的选项集之前,并被视为一个空值。 (这就是为什么我使用 None 作为与 self.blank_choice 选择关联的值,因为它在 django.core.validators.EMPTY_VALUES 元组中)。

要使用它,请使用这个 ChoiceField 而不是 Django 提供的那个,并为 blank_choice 传入一个值,例如
from django import forms
from myproject.formfields import ChoiceField

NAMES = (
    ('brad', 'Brad'),
    ('sam', 'Sam'),
)

class MyForm(forms.Form):
    names = ChoiceField(choices=NAMES, blank_choice='Please choose:')

关于python - 在 Django 的 "Please choose:"小部件中显示 `Select`,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5522339/

10-14 15:13
查看更多