2014-09-01 68 views
2

獲取錯誤「AddVideoFormFormSet」對象沒有屬性「字段」。 Blogpost是視頻的外鍵。我需要允許用戶將視頻添加到他們的博客帖子,但該表單允許用戶將視頻添加到任何博客帖子。有什麼想法嗎?Formset對象 - 對象沒有屬性「字段」

views.py

@login_required 
def addvideo(request): 
    user = request.user 
    theform = AddVideoForm 
    UploadFormSet = formset_factory(theform, extra=1) 
    if request.method == "POST": 
     formset = UploadFormSet(request.POST) 
     if formset.is_valid() : 
      for form in formset.cleaned_data: 
        video = form['video'] 
        title = form['title'] 
        blogpost = form['blogpost'] 
        description = form['description'] 
        video = Video(
         title = title, 
         video= video, 
         blogpost=blogpost, 
         description=description 
         ) 
        video.user = request.user 
        video.save() 

      return HttpResponseRedirect("/%s/%s/" % (user, blogpost.slug)) 

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

    return render_to_response('video/add_video.html', dict(formset=formset), context_instance=RequestContext(request)) 

forms.py

from django import forms 
from main.models import Blogpost 
from .models import * 

class AddVideoForm(forms.ModelForm):   
    class Meta: 
     model = Video 
     fields = ['title', 'blogpost', 'video', 'description'] 

回答

2

一個formset包含幾種形式。嘗試改變:

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

由:

for form in formset: 
    form.fields['blogpost'].queryset = Blogpost.objects.filter(user=user) 

要足夠多。