Django错误:字符串索引必须是整数,而不是str

时间:2014-09-01 06:05:19

标签: python django formset

获取此错误。如何更改POST formset数据以确保实际保存图像?

/ photos / add_photos /上的TypeError  字符串索引必须是整数,而不是str  请求方法:POST  请求网址:/ photos / add_photos /  Django版本:1.6.5  异常类型:TypeError  例外价值:
 字符串索引必须是整数,而不是str

@login_required
    def addimage(request):
        user = request.user
        blogposts = Blogpost.objects.filter(user=user)
        imageformset = formset_factory(Image, AddImageForm,extra=1)
        if request.method == "POST":
            formset = imageformset(request.POST, request.FILES)
            print formset
            if formset.is_valid() :
                for form in formset.cleaned_data:
                        image = form['image']
                        title = form['title']
                        blogpost = form['blogpost']
                        description = form['description']
                        photo = Image(
                            title = title,
                            image= image,
                            blogpost=blogpost,
                            description=description,
                            )
                        photo.user = request.user
                        photo.save()

                        messages.success(request, 'We did it. Pictures are on the interwebs!')
                        return HttpResponseRedirect("/%s/%s/" % (user, blogpost.slug))
            else:
                messages.error(request, 'Oh no! Something went wrong. Try again.')
                return HttpResponseRedirect('/photos/add_photos/')

        else:
            formset = imageformset()
            formset.fields['blogpost'].queryset = Blogpost.objects.filter(user=user)

        return render_to_response('photos/add_photos.html', {
            'formset' : formset,
            'blogpost' : blogposts,
            },
            context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:2)

错误在这一行:

for form in formset.cleaned_data:

您实际需要做的是遍历formset.forms,然后针对每个表单访问cleaned_data

for form in formset:
    image = form.cleaned_data['image']
    ..etc...