【问题标题】:django insert data from 2 tables using a single ModelFormdjango 使用单个 ModelForm 从 2 个表中插入数据
【发布时间】:2011-02-21 19:57:33
【问题描述】:

我想使用 ModelForm 将 2 个表中的数据放入一个表单中,如下所示:

拳头型号:

class Cv(models.Model):
    created_by = models.ForeignKey(User, blank=True)
    first_name = models.CharField(('first name'), max_length=30, blank=True)
    last_name = models.CharField(('last name'), max_length=30, blank=True)
    url = models.URLField(verify_exists=True)
    picture = models.ImageField(help_text=('Upload an image (max %s kilobytes)' %settings.MAX_PHOTO_UPLOAD_SIZE),upload_to='avatar')
    bio = models.CharField(('bio'), max_length=180, blank=True)
    expertise= models.ForeignKey(Expertise, blank=True) 
    date_birth = models.DateField()

第二个模型:

class Expertise(models.Model):
    user = models.ForeignKey(User, blank=True)
    domain = models.CharField(('domain'), max_length=30, blank=True)
    specialisation = models.CharField(('specialization'), max_length=30, blank=True)
    degree = models.CharField(('degree'), max_length=30, blank=True)
    year_last_degree = models.CharField(('year_last_degree'), max_length=30, blank=True)
    lyceum = models.CharField(('lyceum'), max_length=30, blank=True)
    faculty = models.CharField(('faculty'), max_length=30, blank=True)
    references = models.CharField(('references'), max_length=30, blank=True)
    workplace = models.CharField(('workplace'), max_length=30, blank=True)

然后我在 forms.py 中

class CvForm(ModelForm):
   class Meta:
      model = Cv
      fields = ['first_name','last_name','url','picture','bio','date_birth']

class ExpertiseForm(ModelForm):  
   class Meta:
      model = Expertise
      fields = ['domain','specialisation']

关键是我希望将这两种表单合并到一个表单中,当然还有一个提交。所以,我想我应该使用一个 ModelForm 类型的类。但它不起作用(如果我也将专业知识放在 CvForm 中)。 我的表单是从 ModelForm 类自动创建的,这就是为什么我想制作一个 class=> 一个单一的表单。

请帮忙, 非常感谢

【问题讨论】:

    标签: database django forms insert modelform


    【解决方案1】:

    由于从 Expertise 到 CV 有一个外键,因此每个 cv 可能有多个专业知识。所以你应该使用inline formsets来启用它。

    【讨论】:

    • 啊,刚刚注意到你实际上有相反的外键,从 CV 到 Expertise。你确定这就是你的意思吗?这意味着每个专业知识都有多个简历。
    • 不,我发现我错了。我已经制作了另外两个表格:-University 和 -Workplace,针对每个 CV(我想制作这些表格是唯一的方法,因为我有多对多的关系(用户和大学之间,以及用户和工作场所之间))唯一的问题是现在:多对多关系的 django 行为是在我的表单中放置一个下拉列表。我还希望用户有一个文本字段,例如,如果大学不在列表中:D
    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多