在我的views.py中,我有一个像这样的代码:
def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
image = Image.objects.all()
action = "Add"
if request.POST:
if form.is_valid():
clean_post_data(form)
form.save()
action = "Added new product"
return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request))
else:
action = "There was an error. Please go back and try again"
return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request))
return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request))
但是当我运行时,我收到以下错误'list' object has no attribute 'rstrip'
。我做错了什么。
我最初在视图中直接使用for i in form.cleaned_data:
循环(不是在另一个函数中)并且它工作正常,但现在当我尝试它时,我得到与上面相同的错误。 http://dpaste.com/92836/
答案 0 :(得分:1)
clean_post_data
不应该是一个独立的功能。
它应该是表单中的方法,名为clean
。请参阅Form and Field Validation。
答案 1 :(得分:0)
您的表单上很可能有多个具有相同名称的元素。提交时,cleaning_data返回的元素之一是列表
如果你想跳过(或做一些特别的事情)这种情况你需要检查它:
def clean_post_data(form): for i in form.cleaned_data: if('__iter__' in dir(form.cleaned_data[i])): print "skip this element: " + str(form.cleaned_data[i]) else: form.cleaned_data[i] = form.cleaned_data[i].rstrip()