djangodjango-modelsfilefield

Django rename uploaded file: append specific string at the end


models.py

from django.db import models

# validation method to check if file is csv
from django.core.exceptions import ValidationError
def validate_file_extension(value):
    if not value.name.endswith('.csv'):
        raise ValidationError(u'Only CSV files allowed.')

# Create your models here.

class user_file(models.Model):
    user_file_csv = models.FileField(upload_to='documents/user_files/', validators=[validate_file_extension])

forms.py

from django import forms
from .models import user_file
from django.forms import FileInput

class user_file_form(forms.ModelForm):
    class Meta:
        model = user_file
        widgets = {'user_file_csv': FileInput(attrs={'accept': 'text/csv'})}
        fields = ('user_file_csv',)

Thank you!


Solution

  • Maybe you need something like this:

    class FileUploadUtil:
    
        @staticmethod
        def my_files_path(instance, filename):
            name, file_extention = os.path.splitext(filename)
            name = 'prefix-{}-{}-suffix.{}'.format(name, instance.id, file_extention)
            return "my_files/{}".format(name)
    
    
    class MyModel(models.Model):
        # Other fields
        # ...
        my_file = models.FileField(max_length=300, upload_to=FileUploadUtil.my_files_path)