Question

I want to be able to upload images through the admin in Django. But I am having some difficulty

project structure:

/Proj
   /Proj

   /static
      /img
         /albums
            /album1
               img1
            /album2
               img2

Album class:

class Album(models.Model):
    title = models.CharField(max_length = 60)

    def __unicode__(self):
        return self.title

Image class:

class Image(models.Model):
    title = models.CharField(max_length = 60, blank = True, null = True)
    image = models.FileField(upload_to = get_upload_file_name)  <-- !!!!
    tags = models.ManyToManyField(Tag, blank = True)
    albums = models.ForeignKey(Album)
    width = models.IntegerField(blank = True, null = True)
    height = models.IntegerField(blank = True, null = True)
    created = models.DateTimeField(auto_now_add=True)

I THINK my image = models.FileField(upload_to = get_upload_file_name) uses the get_upload_file_name method to place the image in the correct album. This is done through appending to my MEDIA_ROOT which is MEDIA_ROOT = os.path.join(BASE_DIR, 'static')

So the get_upload_file_name method is supposed to do so. But I am not sure how to so.

I think before I can upload I need to create an album first so then I can decide which album the image will go in. A bit lost at this point. Not sure if my Image or Album class is even complete. Thanks for the help!!

Was it helpful?

Solution

The function you pass into upload_to must have the form:

def get_upload_file_name(instance, filename):
    new_file_path_and_name = os.path.join(BASE_DIR, 'static', 'test.txt')
    return new_file_path_and_name

instance is the instance of the Image model you're about to save. That means it has access to all of the other fields that have been populated. filename is the original name of the file that was uploaded. You may choose to use filename or simply return another path + name of your choice.

The official documentation for this is here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top