I'm not sure I understand how the modelformset_factory
library works. I want to present the user a dynamic number of forms to add new items to the database.
My models are like this :
#models.py
class Question(models.Model):
user = models.ForeignKey(User)
text = models.CharField(max_length=100)
class Answer(models.Model):
question = models.ForeignKey(Question)
text = models.CharField(max_length=100)
so a user can define questions and as many answers (choices) to that question.
so in my view, I want to get how many answers they want to add, and create a dynamic formset, like this :
def q_answers(request, qid, howManyAnswersMore):
AnswerModelFormSet = modelformset_factory(Answer, fields=('question','text'), extra = howManyMore)
formset = AnswerModelFormSet()
the problem is, my form set contains all answers in the database (so answer#1 of question#1, a2 of q1, a1 of q2, a2 of q2, etc.)
However, I only want to display answers of the question that is stated in the URL with qid
parameter. How do I filter the Answer items that are only related to that questions?
Also, can I exclude the already existing items and only let the user add new questions?
Thanks for any help!
Either you can add queryset parameter to filter which answer to show:
Or you can extend a BaseModelFormSet class and override its
queryset
property: