Null value in column "width" violates not null constraint while uploading image to django
I'm on Django==5.2.12 and django-imagekit==6.1.0
This is my PostImage model:
class PostImage(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name="images")
image = ProcessedImageField(verbose_name=_("image"), storage=post_image_storage, upload_to=upload_to_post_image_directory, width_field="width", height_field="height", blank=False, null=True, format="JPEG", options={"quality": 100}, processors=[ResizeToFit(width=1024, upscale=False)])
width = models.PositiveIntegerField(editable=False, null=False, blank=False)
height = models.PositiveIntegerField(editable=False, null=False, blank=False)
hash = models.CharField(_("hash"), max_length=64, blank=False, null=True)
thumbnail = ProcessedImageField(verbose_name=_("thumbnail"), storage=post_image_storage, upload_to=upload_to_post_image_directory, blank=False, null=True, format="JPEG", options={"quality": 50}, processors=[ResizeToFit(width=1024, upscale=False)])
media = GenericRelation(PostMedia)
While create a PostImage object, I get thrown the error.
null value in column "width" violates not null constraint.
Since I require the width and height fields to be calculated for further processing,
I don't want to change the fields width and height with null=True. However, just to check what happens after doing it, i did try specifying null=True. The PostImage object does get created but with no values for width and height.
Help appreciated.
This error shows that you have existing record(s) with a null value in width column in your database.
You then probably altered your model to make the width field non-nullable. When you run your Django server, the existing null value for width field(column) will trigger the error because the field has changed state: from nullable to non-nullable.
How to fix?
Either set a default value to populate existing null columns in the database or you can clear all existing records in the database using the command:
python manage.py flush
Im just attempting to create the
PostImageobject and then attempting to first create a PostImage likepost_image = cls.objects.create(image =file)and then extract the value likeimage_width=post_image.width. - Earthling
You are creating a PostImage object, without specifying a value for width (and later height, etc.). Django will not just assume this is the width/height of the image. You will need to inject it yourself. For example with:
class PostImage(models.Model):
# ...
def save(self, *args, **kwargs):
image = self.image
if image:
self.width = image.width
self.height = image.height
# ...
super().save(*args, **kwargs)