Photo upload with Model name in Django

0

I would like help with a task saving images with a custom name and a folder also with the current name, suppose the following Model:

class ProdutoA(models.Model):
    nome_produto_a = models.CharField(max_length=50, verbose_name='Nome do Produto')
    foto_produto_a = models.ImageField(upload_to='produtos', blank=True, null=True, verbose_name='Foto do Produto')
    # ...

class ProdutoB(models.Model):
    nome_produto_b = models.CharField(max_length=50, verbose_name='Nome do Produto')
    foto_produto_b = models.ImageField(upload_to='produtos', blank=True, null=True, verbose_name='Foto do Produto')
    # ...

My question:

How to save the image with the name of the class "ProductX" + "product_name_x", ie name of the model / class which is registered + product name?

For example, suppose there is a product registered in ProductA:

product_name_a = Rice 101

photo_product_a = name_any.jpg

When saving this image, I would like to rename it to:

ProductoA.Arroz101.jpg

Inside a folder called "Product A".

Resulting, therefore, in:

Product A / ProductA.Arroz101.jpg

    
asked by anonymous 11.05.2018 / 18:04

1 answer

0

Use a method in the upload_to

documentation: link

See the example that involves the user_directory_path method. Through instance you have access to the model name.

    
28.05.2018 / 22:53