Set ImageField "upload_to" field of a Product based on their Category name - Django

class Product(models.Model):
    
    category=models.ForeignKey(Category, on_delete=models.CASCADE,
                             related_name='product_category', to_field='category_name')
    name=models.CharField(max_length=255,)
    description=models.CharField(max_length=255)
    
    ***************************************************  
    images=models.ImageField(upload_to='products/'+str(category.category_name), blank=True,null=True)
    ***************************************************
   
    price=models.DecimalField(decimal_places=2,max_digits=7)
    discount=models.DecimalField(decimal_places=2,max_digits=3,
                                 validators=[MinValueValidator(0),MaxValueValidator(0.99)])
    
    def __str__(self):
        return self.name

I want to save images relative to the category name and product name, therefore all products with the same name would be saved in the same file. I don't know if this is the best practice, so please if it shouldn't be like this specify the best way and how can I achieve what I want.

You can add function to set the designation of image upload location

import os
def product_image_location(instance, filename):
    upload_path = f"products/{instance.category.category_name}"
    
    return os.path.join(upload_path, filename)

class Product(models.Model):
    .....
    category=models.ForeignKey(Category, on_delete=models.CASCADE)
    images=models.ImageField(upload_to=product_image_location, blank=True,null=True)
    .....
    

Use function 'product_image_location' as value of 'upload_to'

Back to Top