尝试提交表单时出现以下错误:
argument of type 'NoneType' is not iterable
我的表单类如下:
class requestform(ModelForm):
def __init__(self, *args, **kwargs):
super(requestform, self).__init__(*args,**kwargs)
self.is_update=False
requestedpart = forms.CharField (label="Requested Part", max_length=80, required= True)
librarytype = forms.TypedChoiceField (label="Type", choices = ((1, "Type1"), (2, "Type2"), (3, "Type3")), coerce = lambda x: bool(int(x)), widget = forms.RadioSelect, required= True)
requestformat = forms.TypedChoiceField (label="Format", choices = ((1, "Format1"), (2, "Format2")), coerce = lambda x: bool(int(x)), widget = forms.RadioSelect, required= True)
def clean(self):
if 'requestedpart' not in self.cleaned_data:
return
if not self.is_update:
return self.cleaned_data
class Meta:
model = LibraryRequest
我的观点如下
if request.method == "POST":
formtoaddrequest = requestform(request.POST, request.FILES)
if requestform.is_valid(formtoaddrequest):
new_request = formtoaddrequest.save(commit=False)
new_request.requestadder = request.user
new_request.save()
request.user.message_set.create(message=_("You have saved '%(requestedpart)s'") % {'requestedpart': new_request.requestedpart})
这是我的追溯
Traceback:
File "/Users/AB/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/AB/Desktop/store/project/views.py" in view_requests
201. if formtoaddmodel.is_valid():
File "/Users/AB/Desktop/myenv2/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
121. return self.is_bound and not bool(self.errors)
File "/Users/AB/Desktop/myenv2/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
112. self.full_clean()
File "/Users/AB/Desktop/myenv2/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
269. self._post_clean()
File "/Users/AB/Desktop/myenv2/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
316. self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "/Users/AB/Desktop/myenv2/lib/python2.7/site-packages/django/forms/models.py" in construct_instance
40. or not f.name in cleaned_data:
Exception Type: TypeError at /project/view_requests/
Exception Value: argument of type 'NoneType' is not iterable
了解我可能会收到此错误的原因?
答案 0 :(得分:18)
有很多问题。
您的干净方法应该提出ValidationError
或返回self.cleaned_data
。您的clean()
方法不会引发错误,但会返回None
,更改方式如下:
def clean(self):
if self.cleaned_data and 'requestedpart' not in self.cleaned_data:
raise forms.ValidationError("Some error message")
if not self.is_update:
return self.cleaned_data
return self.cleaned_data
同样,如果您对字段clean_fieldname
有fieldname
,请返回其值:
def clean_fieldname(self):
# ...
return self.cleaned_data['fieldname']
您还可以检查self.cleaned_data
是否为非空
在您看来,表单验证应该是:if requestform.is_valid()
即。没有参数。
答案 1 :(得分:4)
return
方法中不应该有空clean
。如果表单有效,则返回cleaning_data;如果表单无效,则返回forms.ValidationError
。