using rstrip on form.cleaned_data[i] in Django

In my views.py, i have a snippit 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 that, i get the following error 'list' object has no attribute 'rstrip'. What am i doing wrong.

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

Answers


The clean_post_data shouldn't be a stand-alone function.

It should be a method in the form, named clean. See Form and Field Validation.


Most likely you have several elements on your form with same name. When it is submitted one of the elements returned by cleaned_data is a list

If you want to skip (or do something special about) such cases you need to check for it:


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

Need Your Help

Delphi, adding digets

delphi delphi-7

My textbook says I need to make a donation program with three buttons, each representing a certain amount of money. The "Amount donated" should be shown on a label after I press a button.

How to edit Text file in Resources Folder of Window form c#

c# .net winforms window

I am trying to Edit a text file which is consist in resources folder of window form project. C#.