python - 如何使用 Django choicefield 动态设置选项?

标签 python python-3.x django dynamic django-forms

我想设置动态选项。

我使用了 __set_choices 方法,但是,当请求方法是 POST 时, is_valid 方法总是返回 False。

if request.method=='POST':
    _form = MyForm(request.POST)
    if _form.is_valid():
        #something to do

最佳答案

我经常在构造函数中动态设置选项:

class MyForm(BaseForm):
    afield = forms.ChoiceField(choices=INITIAL_CHOICES)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['afield'].choices = my_computed_choices

关于python - 如何使用 Django choicefield 动态设置选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5028731/

相关文章:

python - Model.objects.filter([外部表]).update()

python - Django View 测试

python - 我可以在 Python 中构建 TensorFlow 可服务对象吗

python - OpenCV 和 Python : Face Detection using haarcascades is detecting many boxes as eyes.

python - 通过组python组合多维数组

Python 3 : write method vs. os.write 返回的字节数

python - ZMQ : "Resource temporarily unavailable" when connecting zmq socket

Python urllib 卡住特定的 URL

python-3.x - 如何使用训练好的网络作为另一个网络keras的分支?

django - 如何将所有迁移/添加到 django 中的 git .gitignore 文件?