Unique file name in django

  1. In your Django model, import the necessary modules:
from django.db import models
import uuid
  1. Add a unique field to your model, typically in the form of a UUID field:
class YourModel(models.Model):
    unique_file_name = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  1. Create and apply a migration to update the database schema with the new field:
python manage.py makemigrations
python manage.py migrate
  1. In your views or wherever you handle file uploads, generate a unique file name using the UUID field:
from uuid import uuid4
from django.utils import timezone

def generate_unique_file_name(instance, filename):
    now = timezone.now()
    filename = f"{now.year}/{now.month}/{now.day}/{uuid4()}{filename[-4:]}"
    return filename
  1. In the FileField or ImageField of your model, use the upload_to attribute to specify the function for generating unique file names:
class YourModel(models.Model):
    unique_file_name = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    uploaded_file = models.FileField(upload_to=generate_unique_file_name)
  1. Update your templates or serializers to display or handle the unique file name accordingly.

Now, every time a file is uploaded for the YourModel model, it will be saved with a unique file name generated using a UUID and the generate_unique_file_name function. This ensures uniqueness and helps avoid conflicts when saving files.