Django重复vars /缓存问题?

时间:2010-04-08 22:40:24

标签: python django wsgi

我正在尝试为Django构建一个更好/更强大的表单类。除了这些子表格之外,它运作良好。实际上,它在我重新启动apache后正常工作,但在我刷新页面几次之后,我的HTML输出开始如下所示:

<input class="text" type="text" id="pickup_addr-pickup_addr-pickup_addr-id-pickup_addr-venue" value="" name="pickup_addr-pickup_addr-pickup_addr-pickup_addr-venue" />

pickup_addr-部分开始重复多次。我正在寻找可能导致这种情况发生的prefix代码周围的循环,但是当我刷新页面时输出甚至不一致,所以我觉得有些东西在某个地方被缓存,但我甚至无法想象一下这是可能的。初始化类时应该重置prefix var,不是吗?除非它以某种方式初始化某些东西?

class Form(object):
    count = 0
    def __init__(self, data={}, prefix='', action='', id=None, multiple=False):
        self.fields = {}
        self.subforms = {}
        self.data = {}
        self.action = action
        self.id = fnn(id, 'form%d' % Form.count)
        self.errors = []
        self.valid = True
        if not empty(prefix) and prefix[-1:] not in ('-','_'): prefix += '-'

        for name, field in inspect.getmembers(self, lambda m: isinstance(m, Field)):
            if name[:2] == '__': continue
            field_name = fnn(field.name, name)
            field.label = fnn(field.label, humanize(field_name))
            field.name = field.widget.name = prefix + field_name + ife(multiple, '[]')
            field.id = field.auto_id = field.widget.id = ife(field.id==None, 'id-') + prefix + fnn(field.id, field_name) + ife(multiple, Form.count)
            field.errors = []

            val = fnn(field.widget.get_value(data), field.default)

            if isinstance(val, basestring):
                try:
                    val = field.coerce(field.format(val))
                except Exception, err:
                    self.valid = False
                    field.errors.append(escape_html(err))

            field.val = self.data[name] = field.widget.val = val

            for rule in field.rules:
                rule.fields = self.fields
                rule.val = field.val
                rule.name = field.name

            self.fields[name] = field

        for name, form in inspect.getmembers(self, lambda m: ispropersubclass(m, Form)):
            if name[:2] == '__': continue
            self.subforms[name] = self.__dict__[name] = form(data=data, prefix='%s%s-' % (prefix, name))

        Form.count += 1  

如果您需要更多代码,请告诉我......我知道这很多,但我无法弄清楚是什么导致了这个问题!我甚至没有使用任何缓存中间件。


首先复制/克隆字段会改为输出:

<label for="None">None</label>
<input class="text" type="text" id="id-pickup_address-venue" value="" name="pickup_address-venue" />

field.namefield.label的设置方式完全相同......事实上field.id正确显示在<input>上,但同样的值突然消失了我尝试打印标签....区别在于<input>类是由Widget类打印的,而label是直接从我的模板打印出来的......我是猜测是......哦,我明白了, 一个仍然指的是未设置的类级/静态字段,而不是实例字段......

1 个答案:

答案 0 :(得分:1)

你可能正在声明你的表格:

class SomeForm(Form):
    someField = Field(....)
    ...

现在,这意味着someField的一个实例实际上将在所有SomeForm个实例之间共享。在__init__中,您正在更改字段的属性,这将影响所有表单,而不仅仅是当前表单,包括将来创建的表单。

要解决此问题,您可以为每个实例制作字段的副本:

field = copy(field)  #maybe you need deepcopy instead
setattr(self, name, field)   

然后更改副本的属性。