Django格式错误 [英] Django form error

查看:102
本文介绍了Django格式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pre> 类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()
除了:
打印sys.exc_info()

#=>(< type'exceptions.AttributeError'> ;, AttributeError (JobForm对象没有属性clean_data),< traceback对象在0x1029dbb48>)

尝试验证:

  if form.is_valid():
form.save()
else:
print'error'
print form.errors,len(form.errors)
#=> 'error'
#=> 0

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

解决方案

您的表单绝对没有约束。了解绑定和未绑定表单



从该文档中:


要将数据绑定到表单,传递字典中的数据作为第一个参数 Form类构造函数


这意味着模型中的一个字段的更改也不会使该表单被绑定。你必须通过构造函数显式地传递这些值。但是:


请注意,传递空字典会创建一个绑定表单数据


并考虑这个


如果您有一个绑定的Form实例,并且想要以某种方式更改数据,或者如果要将未绑定的Form 实例绑定到某些数据,创建另一个Form实例。没有办法在Form实例中更改数据。创建表单实例后,您应该考虑其数据 immutable ,无论是否有数据。


如果您验证未绑定表单:


验证没有数据的表单是无意义的,为了记录,以下是未绑定表单会发生什么:



>>> f = ContactForm()

>>> f.is_valid()

False

>> > f.errors

{}



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

That was my form, now trying to save it will raise an exception, and trying to validate it just fails with no errors....

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>)

Tried to validate it:

if form.is_valid():
    form.save()
else:
    print 'error'
    print form.errors, len(form.errors)
#=> 'error' 
#=> 0

So the form isn't valid, but the there are no errors! Any idea?

解决方案

Your form is definitely not bound. Read about Bound and Unbound forms.

From that documentation:

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

That means that also the change of a field in your model doesn't make the form bound. You have to pass those values explicitly via the constructor. But:

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

and consider this

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.

If you validate an unbound form:

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格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆