Answer the question
In order to leave comments, you need to log in
How to make a dynamic path in Django imagefield?
Faced a problem, can't dynamically assign path
in models.py
class PhotoAlbom(models.Model):
...
photo = models.ImageField()
in views.py
photo = request.FILES['file']
how to dynamically assign path photo in views.py?
I'm new to django, I don't understand
much Thank you in advance
Answer the question
In order to leave comments, you need to log in
File save path?
create functions.py file for example
from django.utils.deconstruct import deconstructible
import uuid
import os
@deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
ext = filename.split('.')[-1]
# set filename as random string
filename = '{}.{}'.format(uuid.uuid4(), ext)
# return the whole path to the file
return os.path.join(self.path, filename)
from .functions import PathAndRename
upload_photo = PathAndRename("images/photos")
class PhotoAlbom(models.Model):
photo = models.ImageField(upload_to=upload_photo)
photo = models.ImageField(upload_to='documents/%Y/%m/%d')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question