从多个模型创建模型表单以添加到数据库?

时间:2018-09-21 09:59:20

标签: python django forms django-models

在我的postgressql数据库中,有表:

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

我想使用所有这些表创建一个modelform,以便向数据库中添加新的问题和响应,然后将其链接到主题,位置和客户(这3个将是{{1} },从dropdownlist中获取数据。

我已经成功地创建了db来回答问题,但尝试提交时却得到了modelform

代码如下:

"null value in column "Question_id" violates not-null constraint"

1 个答案:

答案 0 :(得分:1)

在视图中检查is_valid()后,请执行以下操作:

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

如果不指定外键Question,就无法保存Response对象。因此,请在rform.save中传递参数commit=False,以使其尚未真正保存到数据库中。然后将外键的值添加到新创建的Response对象中,需要外键,否则您将获得IntegrityError。然后将其保存到数据库中。