我的看法讓我現在看看我是否有兩個問題,它向我展示了兩種形式。我希望我現在可以實例化我的兩個表單,每個表單都有一個問題。以便用戶不再僅僅回答沒有選擇的問題...如何實例化一個formset的字段以預先填充?
我的看法。潘岳:
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
})
我的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)是否可以放置這樣的過濾器?
試過來看待這個? http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset –
我只是看看,但我不認爲這對應於預填充 –