gpt4 book ai didi

Django 表单错误

转载 作者:行者123 更新时间:2023-12-04 13:07:39 25 4
gpt4 key购买 nike

class JobForm(forms.ModelForm):
class Meta:
model = models.Job

那是我的表单,现在尝试保存它会引发异常,并且尝试验证它只是失败且没有错误......
job = get_object_or_404(models.Job, pk=1)
form = forms.JobForm(instance = job)
try:
form.save()
except:
print sys.exc_info()

#=>(<type 'exceptions.AttributeError'>, AttributeError("'JobForm' object has no attribute 'cleaned_data'",), <traceback object at 0x1029dbb48>)

试图验证它:
if form.is_valid():
form.save()
else:
print 'error'
print form.errors, len(form.errors)
#=> 'error'
#=> 0

所以表格无效,但没有错误!
任何的想法?

最佳答案

您的表格绝对不受约束。阅读 Bound and Unbound forms .

从该文档中:

To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor.



这意味着模型中字段的更改也不会使表单绑定(bind)。您必须通过构造函数显式传递这些值。但:

Note that passing an empty dictionary creates a bound form with empty data



并考虑这一点

If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.



如果您验证 未绑定(bind)形式:

It's meaningless to validate a form with no data, but, for the record, here's what happens with unbound forms:

>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors

{}

关于Django 表单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2393348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com