Upload photo with Model name in Django

Would like help for a task of 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 doubt:

How to save the image with the class name "Productox" + "product_name", i.e. the name of the model/class to which it is registered + product name?

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

Product Name_a = Rice 101

Foto_product_a = nameany.jpg

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

Producto.Rice 101.jpg

Inside a folder called "product a".

Thus resulting in:

Product To / Producta.Rice 101.jpg

Author: HWarlley Massafera, 2018-05-11

1 answers

Use a method in the field upload_to

Documentation: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.FileField.upload_to

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

 1
Author: Madalosso, 2018-05-28 20:53:26