F
F
Friend2016-05-09 17:41:33
Django
Friend, 2016-05-09 17:41:33

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

2 answer(s)
S
sim3x, 2016-05-09
@sim3x

<img src="{{ photomodel.photo.url }}">

I
intelligence, 2016-05-09
@intelligence

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)

Then in models.py
from .functions import PathAndRename

upload_photo = PathAndRename("images/photos")
class PhotoAlbom(models.Model):
    photo = models.ImageField(upload_to=upload_photo)

You can pass any parameters to the function after editing.
Or a simple way:
photo = models.ImageField(upload_to='documents/%Y/%m/%d')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question