Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create year/month/day structure when uploading files with django

Tags:

python

django

am using a basic imagefield and upload_to function to point to my destination folder. I was wondering if there is something i can use to create folder structure with year/month/day on upload date or something..

regards,

like image 929
Mo J. Mughrabi Avatar asked Aug 31 '11 08:08

Mo J. Mughrabi


2 Answers

https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield

For example, say your MEDIA_ROOT is set to '/home/media', and upload_to is set to 'photos/%Y/%m/%d'.
The '%Y/%m/%d' part of upload_to is strftime formatting.

  1. %Y is the four-digit year.
  2. %m is the two-digit month.
  3. %d is the two-digit day.

If you upload a file on Jan. 15, 2007, it will be saved in the directory /home/media/photos/2007/01/15.

like image 93
Tomasz Wysocki Avatar answered Sep 30 '22 15:09

Tomasz Wysocki


fist of all, check this out: http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/ look for "Attempt 4" (control + f on the page) so you can see how to create a function for a dynamic upload.

then, to create your path, you have to use the datetime module:

from datetime import date
today = date.now()
today_path = today.strftime("%Y/%m/%d") ## this will create something like "2011/08/30"

you now have your path, better if you join it with your base path and filename (base path is your images folder)

os.path.join(MEDIA_ROOT, today_path, filename)

this will give you something like /path/to/images/2011/08/30/filename.jpg

The first link is really important.

like image 40
Samuele Mattiuzzo Avatar answered Sep 30 '22 16:09

Samuele Mattiuzzo