models.py
class OtherData(models.Model):
title = models.CharField(max_length=120)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
class ProductImage(models.Model):
otherdata = models.ForeignKey(OtherData)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
image = models.FileField(blank=True, null=True, upload_to='images/')
我正在寻找在otherdata实例上保存图像,获得完整性错误NOT NULL constraint failed
。我正在使用模型表单来保存数据。我尝试在 views.py 中使用格式有效的方法,但仍然是相同的错误。
def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
instance.otherdata_id = self.kwargs.get('pk')
return super(ImageCreateView, self).form_valid(form)
期待寻求帮助,谢谢。
答案 0 :(得分:0)
你可以尝试这个吗,你可以从pk
获得 OtherData实例def form_valid(self, form):
instance = form.save(commit=False)
instance.user = self.request.user
instance.otherdata = OtherData.objects.get(pk=self.kwargs.get('pk'))
return super(ImageCreateView, self).form_valid(form)
以及model.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):
otherdata = models.ForeignKey(OtherData)
user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='product_image')
image = models.FileField(blank=True, null=True, upload_to='images/')