2014-09-01 91 views
0

獲取此錯誤。如何更改POST formset數據以確保圖像實際得到保存?Django錯誤:字符串索引必須是整數,而不是str

類型錯誤在/照片/ add_photos/ 字符串索引必須是整數,而不是str的 請求方法:POST 請求URL:/照片/ add_photos/ Django的版本:1.6.5 異常類型:類型錯誤 異常值:
字符串的索引必須是整數,而不是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)) 

回答

2

的錯誤是在這一行:

for form in formset.cleaned_data: 

你真正需要做的是通過迭代formset.forms,然後爲每個表單訪問cleaned_data

for form in formset: 
    image = form.cleaned_data['image'] 
    ..etc... 
相關問題