Home > Enterprise >  Django: how to upload media files to different folders?
Django: how to upload media files to different folders?

Time:07-02

I want to save file in automatically created folder related with Employee id_number like:

media->employee->attachments->emp001->emp001.pdf

models.py

from django.db import models        
class Employee(models.Model):
      id_number = models.CharField(primary_key=True, null=False, blank=False, unique=True, max_length=15)
      full_name = models.CharField(max_length=255, null=False, blank=False)
      name_with_initials = models.CharField(max_length=255, null=False, blank=False)
      surname = models.CharField(max_length=255, null=False, blank=False)
      phone = models.CharField(max_length=15, null=False, blank=False)
      dob = models.DateField(null=False, blank=False)
      gender = models.CharField(max_length=10, null=False, blank=False)
      email = models.EmailField()
      address = models.CharField(max_length=255, null=False, blank=False)
        
class EmployeeAttachments(models.Model):
      employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
      cv = models.FileField(upload_to=f'employee/attachments/', max_length=100)

can any one tell me how to do this in django, django-rest-framework

CodePudding user response:

This will change a path of cv on EmployeeAttachments according to your Employee id

def facility_path(instance, filename):
    return f'attachments/employee/emp{instance.employee.id}/emp{instance.employee.id}.pdf'

class EmployeeAttachments(models.Model):
      employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
      cv = models.FileField(upload_to=facility_path, max_length=500)
  • Related