·

Django ImageField max_length error when uploading image

Published at 2024-06-07 22:05:31Viewed 424 times
Professional article
Please reprint with source link

I'm using Django 4.2. I have a model whose fields containing ImageField, for example:

class Example(models.Model)
    image = models.ImageField(
          blank=True,
          upload_to=my_image_path,
      )

When I uploaded my image, I got this error from django: Ensure this filename has at most 100 characters (it has 107).

Taken from the Django documentation:

FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.

And note that ImageField is a subclass of FileField:

Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image.

ImageField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.

Therefore, we just need to simply add max_length argument into the ImageField like ordinary CharField:

class Example(models.Model)
    image = models.ImageField(
          blank=True,
          upload_to=my_image_path,
          max_length=500
      )

After this, don't forget to update it in your database:

python manage.py makemigrations
python manage.py migrate


0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved