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/
Asked by: Alfred954 | Posted: 28-01-2022
Answer 1
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.
Answer 2
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()Answered by: Kellan528 | Posted: 01-03-2022
Similar questions
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python