为什么他不认识我的观点实例"访问"在我的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),
答案 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