Lloyd
Lloyd

Reputation: 161

Create modelform from multiple models to add to database?

In my postgressql database I have tables:

class Topic(models.Model):
    Definition = models.TextField(default='Definition')
    Name = models.TextField(default='Name')

    def __str__(self):
       return self.Name

class Question(models.Model):
    Statement = models.TextField(default='Question')

    def __str__(self):
        return self.Statement

class Planit_location(models.Model):
    Planit_location = models.CharField(max_length=255, default='Planit_location')

    def __str__(self):
        return self.Planit_location

class ClientDetail(models.Model):
    Sector = models.ForeignKey(Sector, on_delete=models.CASCADE)
    Client_name = models.CharField(max_length=255, default='Client_name')

    def __str__(self):
        return self.Client_name

class Response(models.Model):
    Question = models.ForeignKey(Question, on_delete=models.CASCADE)
    Topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    Response = models.TextField(default='Response')
    Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
    Planit_Location = models.ForeignKey(Planit_location, on_delete=models.CASCADE)
    Image = models.ForeignKey(Image, on_delete=models.CASCADE)

    def __str__(self):
        return self.Response

I want to create a modelform using all these tables so I can add new questions and responses to my database, which are then linked to a topic, location and client (these 3 will be a dropdownlist from data in db).

I have managed to create a modelform for just question and response but when I try to submit it I get "null value in column "Question_id" violates not-null constraint"

Here is the code:

 if request.method == 'POST':
    qform = QuestionForm(request.POST)
    rform = ResponseForm(request.POST)
    if qform.is_valid() and rform.is_valid():
        qf = qform.save()
        rf = rform.save()
        return render(request, 'app/adddatatest.html', {
           "qform": QuestionForm(),
           "rform": ResponseForm(),
        })

Upvotes: 1

Views: 67

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

After checking for is_valid() in view do this:

qf = qform.save() # Goes to database
rf = rform.save(commit=False) # Doesn't goes to database
rf.Question = qf # gets required attribute
rf.save() # then goes to database

You can't save Response object without specifying the the foreign key Question. So in rform.save pass argument commit=False to not actually saving it in database yet. Then add the value for the foreign key to the new created Response object, foreign key is required otherwise you will get IntegrityError. Then finally save it to the database.

Upvotes: 1

Related Questions