如何在django模型表单中自动添加外键

时间:2017-09-15 16:18:38

标签: python django

models.py

class OtherData(models.Model):
  title = models.CharField(max_length=120)
  user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='other_data')

class ProductImage(models.Model):
  other_data = models.ForeignKey(OtherData, verbose_name='Select title')
  user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product_image')
  image = models.FileField(blank=True, null=True, upload_to='images/')
  featured = models.BooleanField(default=False)

我想要的是自动将图像添加到otherdata实例。我尝试编写views.py如下。

def image_create(request, id=None):
  other_data = get_object_or_404(OtherData, id=id)
  form =ImageForm(request.POST or None)
  if form.is_valid():
      instance=form.save(commit=False)
      instance.other_data = other_data
      instance.save()

但在/ image / add /

中获取错误IntegrityError

NOT NULL约束失败:cars_trucks_productimage.other_data_id

0 个答案:

没有答案