Formset对象 - 对象没有属性'fields'

时间:2014-09-01 09:01:34

标签: python django django-forms

获取错误' AddVideoFormFormSet'对象没有属性'字段'。 Blogpost是一个ForeignKey to Video。我需要允许用户将视频添加到他们的博客帖子中,但该表单允许用户将视频添加到任何博客帖子。有什么想法吗?

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']

1 个答案:

答案 0 :(得分:2)

FormSet包含多个表单。尝试改变:

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

由:

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