如何使用依赖于django中过滤器外键的视图的过滤器

时间:2016-02-22 12:33:17

标签: python django forms django-forms

我定义了表单的 init 方法,以便能够根据我所在的页面过滤我的问题... 在我的观点中,我已经通过以下行执行此请求:

questions = Question.objects.filter(page=instance)

这会检索我页面上的任何问题,或者我... 我希望我可以在我的表单中为显示问题做同样的事情..

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)

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
     })

这是我的表单,我想更改我的过滤器

class ReplyForm(forms.ModelForm):
    class Meta:
        model = Reply
        exclude = ('user','creationDate')
    def __init__(self, *args,**kwargs):
        super (ReplyForm,self ).__init__(*args,**kwargs)
        question = kwargs.get('question')
        self.fields['question'].queryset = Question.objects.filter()

我不知道如何操作过滤器,但这次是在我的ModelForm 中 我在哪里替换questions = Question.objects.filter(page=instance)

如何在ModelForm中将实例作为过滤器传递?

0 个答案:

没有答案