Last active
May 31, 2019 18:32
-
-
Save chhantyal/5370749 to your computer and use it in GitHub Desktop.
get dynamic upload path and slugify in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'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
Thanks for the example, but if you don't like hard coding things, you should probably use methods from os.path: