Custom File Upload Path

A snippet showing how to use upload_to with a callable in Django models.


# models.py
import os
from django.db import models

def user_directory_path(instance, filename):
    return f'user_{instance.user.id}/{filename}'

class UserFile(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    file = models.FileField(upload_to=user_directory_path)
      
Explanation:
  • Files are uploaded into MEDIA_ROOT/user_/filename.
  • FileField is used to upload files to the user_/filename directory.
  • ForeignKey is used to link the file to a user.
  • Category Static & Media Files
  • Total Views 416
  • Last Modified 25 April, 2026
  • Tags #media #upload path #files #models
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.