如何实例化一个formset的字段来预先填充?

时间:2016-02-12 13:59:00

标签: django django-forms populate formset formsets

我的观点现在让我看看我是否有两个问题,它向我展示了两个表格。我希望我现在能够实例化我的两个表格,每个表格一个问题。因此,用户不再只是回答问题而不选择...

  

我的观点。 py:

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, queryset=Reply.objects.none())
    if request.method == 'POST':  
        formset = ReplyFormSet(request.POST, queryset=Reply.objects.none())
        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
     })
  

my models.py:

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)
  

和我的forms.py:

class ReplyForm(forms.ModelForm):
    class Meta:
        model = Reply
        exclude = ('user','creationDate')

我想使用此过滤器预先填充字段“问题” - > Question.objects.filter(page = instance)是否可以设置这样的过滤器?

1 个答案:

答案 0 :(得分:-1)