Skip to content

Instantly share code, notes, and snippets.

@chhantyal
Last active May 31, 2019 18:32
Show Gist options
  • Save chhantyal/5370749 to your computer and use it in GitHub Desktop.
Save chhantyal/5370749 to your computer and use it in GitHub Desktop.
get dynamic upload path and slugify in Django
from django.db import models
from django.utils.text import slugify
class Document(models.Model):
def get_upload_path(self, filename):
"""
Returns the upload path for docs
"""
filename = filename.split('.')
extension = filename.pop()
name = ''.join(filename)
return "documents/%s/%s.%s" % (self.post.pk, slugify(name), extension)
document_file = models.FileField(upload_to=get_upload_path)
@ironhouzi
Copy link

Thanks for the example, but if you don't like hard coding things, you should probably use methods from os.path:

def get_upload_path(self, filename):
    name, ext = os.path.splitext(filename)
    return os.path.join('documents', self.post.pk, slugify(name), ext)

@guinunez
Copy link

guinunez commented Jun 14, 2017

ironhouzi's solution worked almost perfectly for me, but I had to fix a couple of things (casting to string and concatenating the extension), here is my version:

    def get_upload_path(self, filename):
        name, ext = os.path.splitext(filename)
        return os.path.join('documents', str(self.post.pk), slugify(name) + ext)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment