当我在 Admin 中打开“Placerating”条目,并在对任何字段进行更改后尝试保存它时,Django admin 在“Pic”字段上方显示“This field is required”。
class Placerating(models.Model):
theplace = models.ForeignKey('ThePlace', on_delete=models.CASCADE, null=True, related_name='placeratings')
pic = models.OneToOneField('fileupload.Picture', on_delete=models.SET_NULL, null=True)
def __unicode__(self):
return self.theplace.name
class Picture(models.Model):
def set_upload_to_info(self, path, name):
self.upload_to_info = (path, name)
file = ImageField(max_length=500, upload_to=user_directory_path)
def filename(self):
return os.path.basename(self.file.name)
theplace = models.ForeignKey(ThePlace, null=True, blank=True, related_name='pictures')
def __unicode__(self):
return str(self.id)
def save(self, *args, **kwargs):
super(Picture, self).save(*args, **kwargs)
我创建的条目没有问题,所以我不明白为什么管理员现在要求填写此字段。
最佳答案
来自docs关于模型字段的 null
参数:
For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).
管理员使用表单来创建和编辑,因此您需要在您希望能够在管理员中留空的字段中使用 blank=True
。
关于python - Django 模型 OneToOneField : "This field is required" error in admin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41770280/