今天我开始阅读django.forms
. 该 API 似乎很容易使用,我开始尝试使用它。然后我开始尝试,django.forms.ModelForm
但我真的看不出哪里出错了。
我的问题从这里开始:使用.form
instance
我的模型是
class Process(models.Model):
key = models.CharField(max_length=32, default="")
name = models.CharField(max_length=30)
path = models.CharField(max_length=215)
author = models.CharField(max_length=100)
canparse = models.NullBooleanField(default=False)
last_exec = models.DateTimeField(null = True)
last_stop = models.DateTimeField(null = True)
last_change = models.DateTimeField(null = True, auto_now=True)
我的表格是
class ProcessForm(ModelForm):
class Meta:
model = Process
fields = ('name', 'path', 'author')
我只想要name
,path
和author
字段,因为其他字段是在保存模型时自动设置的。无论如何,在我的测试数据库中,我已经有条目,并且我选择了一个字段全部设置且有效的条目。
在文档中,您可以阅读:
# Create a form to edit an existing Article.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(instance=a)
>>> f.save()
很好,我想用我自己的代码做同样的事情:
>>> from remusdb.models import Process
>>> from monitor.forms import ProcessForm
>>>
>>> proc = Process.objects.get(name="christ")
>>> pf = ProcessForm(instance=proc)
>>> pf.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shaoran/devpython/lib/python2.6/site-packages/django/forms/models.py", line 364, in save
fail_message, commit, construct=False)
File "/home/shaoran/devpython/lib/python2.6/site-packages/django/forms/models.py", line 87, in save_instance
save_m2m()
File "/home/shaoran/devpython/lib/python2.6/site-packages/django/forms/models.py", line 78, in save_m2m
cleaned_data = form.cleaned_data
AttributeError: 'ProcessForm' object has no attribute 'cleaned_data'
>>> pf.is_bound
False
>>> pf.is_valid()
False
即使proc
是一个有效Process
的对象,表单对象似乎也不同意我的看法。如果我像下一个例子那样做
>>> post = { "name": "blabla", "path": "/somewhere", "author": "me" }
>>> pf = ProcessForm(post, instance=proc)
>>> pf.is_bound
True
>>> pf.is_valid()
True
>>> pf.cleaned_data
{'path': u'/somewhere', 'name': u'blabla', 'author': u'me'}
然后它就像文档的第三个示例一样工作。
我是否遗漏了什么或文档中有错误?还是我的Model
代码有些错误?
这是内容proc
过程。dict {'name': u'christ', 'last_stop': datetime.datetime(2012, 10, 5, 16, 49, 13, 630040, tzinfo=), 'author': u'unkown', '_state': , 'canparse': False, 'last_exec': datetime.datetime(2012, 10, 5, 16, 49, 8, 545626, tzinfo=), 'key': u'aed72c9d46d2318b99ffba930a110610', 'path': u'/home /shaoran/projects/cascade/remusdb/test/samples/christ.cnf', 'last_change': datetime.datetime(2012, 10, 5, 16, 49, 13, 631764, tzinfo=), 'id': 5}