Using rstrip in form.cleaned_data [i] in Django

In my view.py, I have a piece of code like this:

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

      

But when I run this I get the following error 'list' object has no attribute 'rstrip'

. What am I doing wrong.

I originally had the loop for i in form.cleaned_data:

directly in the view (and not in another function) and it worked fine, but now when I try I get the same error as above. http://dpaste.com/92836/

+1


source to share


2 answers


clean_post_data

shouldn't be a standalone feature.



It must be a named method clean

. See Form and Field Validation .

+1


source


Most likely, you have multiple elements in your form with the same name. When it dispatches, one of the items returned by cleaned_data is a list

If you want to skip (or do something special) in such cases, you need to check it out:



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


source







All Articles