Upload_to File and Images Django.How

Author avatar wrote on 08/06/2022

A folder

class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.FileField(upload_to='uploads/')


Date

class MyModel(models.Model):
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/')


# upload_to Parameter
def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_/
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class MyModel(models.Model):
    upload = models.FileField(upload_to=user_directory_path)

Resources:
  • https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/
  • https://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/index.html