繁体   English   中英

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

[英]Django Error: string indices must be integers, not str

收到此错误。 如何更改POST表单集数据以确保实际保存图像?

/ photos / add_photos /字符串索引处的TypeError必须是整数,而不是str请求方法:POST请求URL:/ 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))

错误在这一行:

for form in formset.cleaned_data:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM