python - 将数据传递到 Django 表单中

标签 python django

class Test(forms.Form):

    def set_choices(self, choices):
        self.choices = choices

    def get_choices(self):
        return self.choices

    options  = forms.ChoiceField(choices=get_choices())

f = Test()
f.set_choices(...)

为什么这不可能?
我还能如何实现将数据传递到类 Test 的目标?
提前致谢。

最佳答案

这是一个基本的 Python 问题。您需要考虑这些命令的执行顺序及其范围。

首先,您定义一个名为 Test 的表单类。该类具有三个属性:set_choices 方法、get_choices 方法和options 字段。这些定义在定义类本身时进行评估。 options 的定义调用 get_choices()。但是,此时范围内没有 get_choices 方法,因为该类尚未定义。

即使您以某种方式设法解决了范围问题,这仍然无法满足您的要求,因为 options 的选择定义是在定义时完成的。即使您稍后调用 set_choicesoptions 仍然具有定义字段时返回的 get_choices 的值。

那么,你到底想做什么?您似乎想在 options 字段上设置动态选择。因此,您应该覆盖 __init__ 方法并在那里定义它们。

class Test(forms.Form):
    options = forms.ChoiceField(choices=())

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None)
        super(Test, self).__init__(*args, **kwargs)
        if choices is not None:
            self.fields['options'].choices = choices

关于python - 将数据传递到 Django 表单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5744327/

相关文章:

Django 1.8 条件注释导致 INNER JOIN 而不是 LEFT OUTER JOIN

python - 如何正确装饰要在 python 中重写的函数?

python - FactoryBoy 重写属性

python - 每月、每年分组的值计数 - Pandas

python - 如何修复 ruby 错误: sh: 1: make: not found

python - 如何在 Django orm 中链接和过滤 3 个表中的数据

python - xmlrpclib、wsapi4plone - 检查用户名和密码

django - union 不在 django Rest 框架中工作?

python - 处理上传图片 django admin python

python - uWSGI 未在 Ubuntu 16 服务器中创建套接字