Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model OneToOneField : "This field is required" error in admin

When I open an entry of "Placerating" in Admin, and try to save it after making a change to any field, Django admin displays "This field is required" above the field "Pic".

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)

I created the entry without problem with a form, so I don't understand why admin would now require this field to be completed.

like image 850
Paul Noon Avatar asked Jan 20 '17 18:01

Paul Noon


1 Answers

From the docs about the null argument to model fields:

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).

The admin uses forms for creation and editing, so you need blank=True in the fields you want to be able to leave blank in the admin.

like image 127
Peter DeGlopper Avatar answered Oct 12 '22 19:10

Peter DeGlopper