Deep
Deep

Reputation: 3076

How and where do I handle file uploads from django admin?

So ive read over the docs and I have come out a little confused. I have a model as such

class Image(models.Model):
name = models.CharField(max_length=80)
file = models.ImageField(upload_to = 'project_images')
description = models.CharField(max_length=30)

def __unicode__(self):
    return self.name

The handling of the file uploads are done through the admin interface, which works but I need to do a few more things to the data based on other fields present when the upload is committed.

Basically the current directory is project_images what i want to do is when saved the images must be placed in ---> project_images/<year>/<month>. The file path saved must reflect this when saved in the database and the filename must also be saved in the name field.

I understand the logic behind doing this;

  1. Check post
  2. Check valid (the ImageField takes care of this already i assume)
  3. Get filename
  4. Get year and month (numbers)
  5. Check if directories exist
  6. If directories dont exist create it, if they do use them
  7. Set the name to the filename
  8. upload and save all

Where am i supposed to specify this? In the model under a save method?

Sorry if this is specified in the docs but this is one area of the docs which just confused me.

Thanks

Upvotes: 3

Views: 1129

Answers (2)

boltsfrombluesky
boltsfrombluesky

Reputation: 422

from django.db import models
import datetime
import os
import uuid
# Create your models here.
def get_file_path(instance,filename):
        ext=filename.split('.')[-1]
        filename="%s.%s" % (uuid.uuid4(),ext)
        return os.path.join(instance.directory_string_var,filename)

class Image(models.Model):
        file=models.ImageField(upload_to=get_file_path)

        now=datetime.datetime.now()
        directory_string_var = 'image/%s/%s/%s/'%(now.year,now.month,now.day)

change your model to above one.

this saves your file with a random name in the folder media/year/month/day.

if you don't want filename to be random just comment out

ext = filename.split('.')[-1] #and 
filename="%s.%s" % (uuid.uuid4(),ext)

Upvotes: 1

karec
karec

Reputation: 56

check this:

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

So in your model, you can just do:

class Image(models.Model):
    name = models.CharField(max_length=80)
    file = models.ImageField(upload_to = 'project_images/%Y/%m')
    description = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

The '%Y/%m' part of upload_to is strftime formatting; '%Y' is the four-digit year and '%m' is the two-digit month

You must check this to:

http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/

I Hope this helped

Upvotes: 0

Related Questions