Django ModelFormSet exclude (or filter) existing items

755 Views Asked by At

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!

1

There are 1 best solutions below

0
On

Either you can add queryset parameter to filter which answer to show:

def q_answers(request, qid, howManyAnswersMore):
    AnswerModelFormSet = modelformset_factory(Answer, fields=('question','text'), extra = howManyMore)
    formset = AnswerModelFormSet(queryset=Transaction.objects.filter(quistion=qid))

Or you can extend a BaseModelFormSet class and override its queryset property:

class BaseAnswerFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseAnswerFormSet, self).__init__(*args, **kwargs)

        #create filtering here whatever that suits you needs
        self.queryset = Answer.objects.filter(question=qid)
def q_answers(request, qid, howManyAnswersMore):
    formset = modelformset_factory(Answer, formset=BaseTransactionFormSet,form=AnswerDateForm, extra=0, can_delete=False)