9

我正在执行一个基本的 Django ModelForm 创建/验证/保存操作。在 Eclipse 调试器下运行代码时调用 is_valid() 时不会调用我的自定义清理方法,并且我在创建表单和调用 is_valid() 之后设置了断点。

我已经多次跟踪 Django 基本代码,似乎 ModelForm 类上的错误字典从未设置为 None,这会触发验证。我怀疑这是由于与访问 ModelForm 的 _errors 属性以显示在变量窗格中的调试器的交互。

当我删除所有断点并让代码自然流动时,我可以通过发出打印语句来证明自定义干净代码正在运行。

这是 Django ModelForm 设计中的缺陷、Eclipse 问题还是我找错了树?

模型.py

from django.db import models

class TestModel1(models.Model):
    field1 = models.CharField(max_length=45)
    field2 = models.IntegerField(default=2)
    field3 = models.CharField(max_length=45, null=True, blank=True)

表格.py

from order.models import TestModel1
from django.forms import ModelForm

class OrderTestForm(ModelForm):

    def clean_field1(self):
        return self.cleaned_data['field1']

    def clean_field2(self):
        return self.cleaned_data['field2']

    class Meta:
        model = TestModel1

我的测试工具:

from forms import OrderTestForm

row = {'field1': 'test value', 'field2': '4', }

ff = OrderTestForm(row)

#ff.full_clean()
if ff.is_valid():
    ff.save()
else:
    print ff.errors
4

3 回答 3

1

如果你尝试:

from order.models import TestModel1
from django.forms import ModelForm

class OrderTestForm(ModelForm):
    class Meta:
        model = TestModel1

    def clean_field1(self):
        value = self.cleaned_data['field1']
        print value 
        return value

    def clean_field2(self):
        value = self.cleaned_data['field2']
        print value 
        return value
于 2012-11-30T18:47:37.850 回答
0

I have found the "answer" which is sort of a non-answer. The exact use case was receiving a CSV file from a customer. After inspection of the customer's actual data file, the data fields were padded with spaces -- many spaces. I trimmed the input and shoved that trimmed dictionary into the form and everything worked. Still does not explain why eclipse choked on this.

于 2012-12-26T14:01:41.587 回答
0

我遇到了同样的问题,并试图深入挖掘并调试框架。

常规表单和模型表单之间可能存在差异,导致它不起作用,但是这个 hack(覆盖is_valid()而不是clean(...))对我有用:

def is_valid(self):
    #run whatever ModelForm validations you need
    return super(OrderTestForm, self).is_valid()
于 2013-02-04T18:15:02.357 回答