开发者

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

开发者 https://www.devze.com 2023-04-01 03:28 出处:网络
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 up开发者_StackOv

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 up开发者_StackOverflow社区load date or something..

regards,


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消