N
N
nurzhannogerbek2018-02-20 21:30:07
Django
nurzhannogerbek, 2018-02-20 21:30:07

What is the correct way to save a file in Django to a specific location?

Hello! Please help me figure it out.
There is a data model Product. Each product has a category. There is also a form for creating a new record, where the user specifies a category and uploads a file.
The question is: how, depending on the selected category (assuming there are only two categories), to specify a specific download location for files outside the MEDIA_ROOT specified in the settings?
Structure:

my_site  <- основная директория, где хранится сам проект
my_site_files  < - Файлы нужно хранить за пределами проекта
      |____ category_1   <- файлы продукции с категорией 1 хранятся здесь
      |____ category_2   <- файлы продукции с категорией 2 хранятся здесь

models.py:
class Product(models.Model):
    file = models.FileField(
        max_length=255,
        blank=True,
        null=True,
        validators=[validate_file_extension]
    )

What I did:
To start, I created an environment variable (PRODUCT_FILE_PATH) with an absolute address to the my_site_files folder. Thought I would use this variable. Further as far as I understood it is necessary to use signals. I started like this, but to be honest I got confused:
@receiver(post_save, sender=Document)
def update_file_path(sender, instance, created, *args, **kwargs):
  if created:
    product_file=instance.file
    old_name=product_file.name
    if not old_name:
      return
    if instance.category==1:
      # Здесь сохранить путь для первой категории
    elif instance.category==2:
      # Здесь сохранить путь для первой категории
    instance.save()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question