ilya
ilya

Reputation: 551

Django - how to make ImageField/FileField optional?

class Product(models.Model):
    ...    
    image = models.ImageField(upload_to=generate_filename, blank=True)  

When I use ImageField(blank=True) and do not select image into admin form, an exception occurs.

In django code you can see this:

class FieldFile(File):
   ....

    def _require_file(self):
        if not self:
            raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)

    def _get_file(self):
        self._require_file()
        ...

Django trac has ticket #13327 about this problem, but seems it can't be fixed soon. How to make these field optional?

Upvotes: 55

Views: 53737

Answers (3)

Amiay Narayan
Amiay Narayan

Reputation: 529

If 'optional' means that you want to be able to disregard the image field altogether. Then blank=True, so do the trick. However, if you are still getting the same error, then this means that you are using it's url either in the template somewhere or you are trying to open the path of the image in models.py or views.py ( may be to resize the image or some other backend preprocessing). That is why it is always suggested to use try - catch block while handling files.

Upvotes: 3

holybull
holybull

Reputation: 2016

blank=True should work. If this attribute, which is False by default, is set to True then it will allow entry of an empty value.

I have the following class in my article app:

class Photo(models.Model):
        imagename = models.TextField()
        articleimage = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)

I make use of the above class in another class by using the ManyToManyField relationship:

class Article(models.Model):
        pub_date = models.DateTimeField(default=timezone.now)
        slug = models.SlugField(max_length=130)
        title = models.TextField()
        photo = models.ManyToManyField(
            Photo, related_name='photos', blank=True)
        author = models.ForeignKey(User)
        body = models.TextField()
        categories = models.ManyToManyField(
            Category, related_name='articles', null=True)

I want to make images in my articles optional, so blank=True in

photo = models.ManyToManyField(Photo, related_name='photos', blank=True)

is necessary. This allows me to create an article without any images if I want to.

Are you using class Product in any relationship? If so, make sure to set blank=True in the relationship you are using.

Upvotes: 51

Nathan
Nathan

Reputation: 2995

Set null=True (see documentation)

class Product(models.Model):
    ...    
    image = models.ImageField(upload_to=generate_filename, blank=True, null=True)

Upvotes: 22

Related Questions