Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django访问传递到窗体的数据_Python_Django_Forms_Django Forms_Django Models - Fatal编程技术网

Python Django访问传递到窗体的数据

Python Django访问传递到窗体的数据,python,django,forms,django-forms,django-models,Python,Django,Forms,Django Forms,Django Models,我的表单中有一个选项字段,在那里我显示过滤后的数据。要过滤数据,我需要两个参数。第一个不是问题,因为我可以直接从对象获取它,但第二个是动态生成的。下面是一些代码: class GroupAdd(forms.Form): def __init__(self, *args, **kwargs): self.pid = kwargs.pop('parent_id', None) super(GroupAdd, self).__init__(*args, **k

我的表单中有一个
选项字段
,在那里我显示过滤后的数据。要过滤数据,我需要两个参数。第一个不是问题,因为我可以直接从对象获取它,但第二个是动态生成的。下面是一些代码:

class GroupAdd(forms.Form):
    def __init__(self, *args, **kwargs):
        self.pid = kwargs.pop('parent_id', None)

        super(GroupAdd, self).__init__(*args, **kwargs)

    parent_id = forms.IntegerField(widget=forms.HiddenInput)
    choices = forms.ChoiceField(
        choices = [
            [group.node_id, group.name] for group in Objtree.objects.filter(
                 type_id = ObjtreeTypes.objects.values_list('type_id').filter(name = 'group'), 
                 parent_id = 50
            ).distinct()] + [[0, 'Add a new one']
        ], 
        widget = forms.Select(
            attrs = {
                'id': 'group_select'
            }
        )
     )
我想更改传递到
Objtree.objects.filter
中的父\u id。正如您所看到的,我尝试了init函数,以及
kwargs['initial']['parent\u id']
,然后用
self
调用它,但这不起作用,因为它超出了范围。。。这几乎是我最后的努力。我需要通过
initial
参数或直接通过
parent\u id
字段访问它,因为它已经保存了它的值(通过
initial
传递)


非常感谢您的帮助,因为我已经没有什么想法了。

在回答您的问题之前,请先回答几个小问题

首先,您的字段可能应该是一个
modelcooicefield
——这需要一个
queryset
参数,而不是一个选项列表,这避免了列表理解获取id和值的需要

其次,使用双下划线表示法遍历关系可以更好地编写获取Objtree对象的查询:

Objtree.objects.filter(type__name='group', parent_id=50)
现在,真正的问题。正如您所注意到的,您不能访问字段声明中的本地或实例变量。这些是类级属性,在定义类时处理(通过元类),而不是在实例化类时处理。因此,您需要在
\uuuu init\uuuu
中完成整个过程

像这样:

class GroupAdd(forms.Form):
    parent_id = forms.IntegerField(widget=forms.HiddenInput)
    choices = forms.ModelChoiceField(queryset=None)

    def __init__(self, *args, **kwargs):
        pid = kwargs.pop('parent_id', None)
        super(GroupAdd, self).__init__(*args, **kwargs)
        self.fields['choices'].queryset = Objtree.objects.filter(
                                              type__name='group', parent_id=pid
                                          )

谢谢,这很有效,但我不能使用
type\uu name='group'
,因为
Objtree
ObjtreeTypes
之间没有关系。我可以添加一个foring键,但现在不需要+1.