Home > Software engineering >  Create multiple entries for one model in a Django modelform
Create multiple entries for one model in a Django modelform

Time:11-06

Sorry if the title is confusing, I can't really think of how else to word it.

I am creating a site where there are many quizzes. Each Quiz model

class Quiz(models.Model):
    
    name = models.CharField(max_length = 80)
    description = models.CharField(max_length = 300)
    num_questions = models.IntegerField(default = 10)
    slug = models.SlugField(max_length = 20)
    img = models.URLField(blank = True) # allow it to be none

    def __str__(self):
        return self.name

    def get_questions(self):
        return self.question_set.all()

looks like this... and it has some attributes like name, description, etc. There are many Question models that have ForeignKey to one Quiz:

class Question(models.Model):

    quiz = models.ForeignKey(Quiz, on_delete = models.CASCADE)
    img = models.URLField(blank = True) # allow none`
    content = models.CharField(max_length = 200)

    def __str__(self):
        return self.content
    
    def get_answers(self):
        return self.answer_set.all()

and then there are some Choice models that have ForeignKey to one Question:

class Choice(models.Model):

    question = models.ForeignKey(Question, on_delete = models.CASCADE)

    content = models.CharField(max_length = 200)
    correct = models.BooleanField(default = False)

Now. I want to create one single ModelForm from which I can create 1 quiz record, and then 10 question records with 4 choice records per question. It would be very nice if they could automatically set their foreignkey to the Question that is being created. How can I go about this? Is it even possible? I don't even know if my wording of this question is making sense because I have a great big idea in my head but no idea how to express it properly in words or code.

Help is appreciated :)

CodePudding user response:

If you have 3 models and you want to show them in a single form in your HTML file. Then you can simply create a model form for each of them and add them in a single <form> tag.

The answer to a similar question is posted here.

CodePudding user response:

If you mean inserting multiple records at the same time, then consider looking at formset factory - https://docs.djangoproject.com/en/3.2/topics/forms/formsets/

  • Related