我希望我可以在我的班级中实例化字段问题当我在模板中调用我的表单时回复
class Page(models.Model):
title = models.CharField(max_length=30)
def __str__(self):
return self.title
class Question(models.Model):
label = models.CharField(max_length=30)
page = models.ManyToManyField(Page)
def __str__(self):
return self.label
class Reply(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(Personne)
answer = models.CharField(max_length=30)
creationDate = models.DateTimeField(default=django.utils.timezone.now)
def __str__(self):
return str(self.answer)
是否可以根据我所在的页面过滤字段我的问题。也就是说,如果我打电话给我的一个访问的页面,我有2个问题,如果我在名为“访问2”的页面中,则在两个问题之间没有选择,并且在这次访问中有3个问题,它给了我选择他的3个问题之间...
我希望能够在调用ReplyForm表单时过滤问题的选择
class ReplyForm(forms.ModelForm):
class Meta:
model = Reply
exclude = ('user','creationDate')
我需要在模型中添加一些内容,我的观点吗?
def access(request, instance):
replies = Reply.objects.all()
pages = Page.objects.all()
numPages = Page.objects.get(pk=instance)
questions = Question.objects.filter(page=instance)
length_questions = len(questions)
logged_user = get_logged_user_from_request(request)
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)
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:
messages.add_message(request, messages.INFO, 'Le formulaire est incorrecte !')
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
})
编辑:
我尝试在表单中定义 init 方法,但我似乎无法使用我的过滤器根据页面显示问题
class ReplyForm(forms.ModelForm):
class Meta:
model = Reply
exclude = ('user','creationDate')
def __init__(self, instance, *args,**kwargs):
super (ReplyForm,self ).__init__(*args,**kwargs)
instance = kwargs.get('instance')
self.fields['question'].queryset = Question.objects.filter(page = instance)
答案 0 :(得分:0)
当您实例化get请求的formset时:
formset = ReplyFormSet(queryset=Reply.objects.none())
您应该将要显示的问题作为查询集传递给它。您可以传递任何查询集,如“formset = ReplyFormSet(instance=Reply.objects.filter(question='foo'))
”或“formset = ReplyFormSet(instance=Reply.objects.exclude(question='bar'))
”
应该做你喜欢的事。