传递数据到django表单 [英] Passing data into django forms

查看:113
本文介绍了传递数据到django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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(...)

为什么这不可能?
我还能如何实现将数据传入课程测试的目标?

提前感谢。

解决方案

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



首先,您定义一个名为Test的表单类。该类有三个属性:一个 set_choices 方法,一个 get_choices 方法和一个选项字段。定义类本身时,会对这些定义进行评估。 选项的定义调用 get_choices()。然而,在这一点上,范围内没有 get_choices 方法,因为该类尚未定义。



甚至如果您以某种方式解决了范围问题,则仍然无法执行所需的操作,因为选项的定义在定义时间完成。即使您以后调用 set_choices 选项仍然具有值 get_choices 在定义字段时返回。



那么你真的想做什么?您似乎想在选项字段上设置动态选项。因此,您应该覆盖 __ 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)
如果选择不是None:
self.fields ['options '] .choices =选择


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(...)

Why isn't this possible?
How else can I achieve the goal of passing data into class Test?
Thanks in advance.

解决方案

This is a basic Python issue. You need to think about the order these commands are executed in, and their scope.

First, you define a form class called Test. That class has three attributes: a set_choices method, a get_choices method, and an options field. These definitions are evaluated when the class itself is defined. The definition of options calls get_choices(). However, there is no get_choices method in scope at that point, because the class is not yet defined.

Even if you somehow managed to sort out the scope issue, this would still not do what you want, because the definition of choices for options is done at define time. Even if you later call set_choices, options still has the value of get_choices that was returned when the field was defined.

So, what do you actually want to do? It seems like you want to set dynamic choices on the options field. So, you should override the __init__ method and define them there.

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

这篇关于传递数据到django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆