Search code examples
pythondjangoimagefield

How can I not put data in ImageField in Django?


I am to store images in imagefield. But I don't want to print out an error even if I don't put an image in ImageField. In other words, I want to leave ImageField null.I also tried null=True and blank=True to do this, but it didn't work properly. What should I do to make it possible? Here is my code.

class post (models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=40)
    text = models.TextField(max_length=300)
    image1 = models.ImageField(blank=True, null=True)
    image2 = models.ImageField(blank=True, null=True)
    image3 = models.ImageField(blank=True, null=True)
    image4 = models.ImageField(blank=True, null=True)
    image5 = models.ImageField(blank=True, null=True)

Solution

  • To correctly use an ImageField() you need to install Pillow with pip install Pillow

    It would be better to make an Image model and reference it with a ForeignKey from your Post model like this:

    from django.db import models
    
    
    class Image (models.Model):
        title = models.CharField(max_length=40)
        text = models.TextField(max_length=300)
        image = models.ImageField(blank=True, null=True)
       
        def __str__(self):
            return self.title
    
        class Meta:
            db_table = 'image'
    
    
    class Post (models.Model):
        author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
        images = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='posts')
        title = models.CharField(max_length=40)
        text = models.TextField(max_length=300)
    
        def __str__(self):
            return self.title
    
        class Meta:
            db_table = 'post'
    
    

    Django will try and upload an image to the Media root, so add the MEDIA_URL to the bottom of your settings.py like this:

    # settings.py 
    
    MEDIA_URL = 'media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    
    

    Dont forget to clear your database and redo your migrations and you should be able to keep the ImageField empty if you want