名称'实例'我的__init__ ModelForm中没有定义

时间:2016-02-22 14:24:01

标签: python django forms modelform

为什么他不认识我的观点实例"访问"在我的ModelForm中?

我有这个错误:name 'instance' is not defined

我的表格:

class ReplyForm(forms.ModelForm):

    def __init__(self, *args,**kwargs):
        super (ReplyForm,self ).__init__(*args,**kwargs)
        self.fields['question'].queryset = Question.objects.get(page=instance)

    class Meta:
        model = Reply

和我的views.py:

def access(request, instance):
    length_questions = len(questions)
    ReplyFormSet = modelformset_factory(model=Reply, form=ReplyForm, extra=length_questions, can_delete=True)
    formset = ReplyFormSet(request.POST)
    if request.method == 'POST':  
        formset = ReplyFormSet(request.POST, request.FILES)
        if formset.is_valid():
            new_instances = formset.save(commit=False)
            for new_instance in new_instances:
                new_instance.user = logged_user
                new_instance.save()
            return HttpResponseRedirect('/baseVisite/')
        else:
            return render_to_response('polls/error.html', context_instance=RequestContext(request))
    else:
        formset = ReplyFormSet(queryset=Reply.objects.none())
    return render_to_response('polls/access.html', {
 'formset': formset,
 'questions':questions,
 'logged_user':logged_user,
 'numPages' : numPages
 })

修改网址:

url(r'^access/(?P<instance>[0-9]+)/$', views.access),

1 个答案:

答案 0 :(得分:0)

变量instance仅在view中定义。 如果您想在__init__的{​​{1}}方法中使用它,则必须明确传递它。

我没有Form的经验,但如果没有,它可能看起来像这样:

形式:

modelformset_factory

查看:

class ReplyForm(forms.ModelForm):

    def __init__(self, *args,**kwargs):
        instance = kwargs.pop('instance')
        super (ReplyForm,self ).__init__(*args,**kwargs)
        self.fields['question'].queryset = Question.objects.get(page=instance)

    class Meta:
        model = Reply