Reputation: 16469
I want my photos to be uploaded to a directory that has the same name as the album they are in. I tried photo = models.ImageField(upload_to=album.title)
but I get the error:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Library/Python/2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Library/Python/2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/bli1/Development/Django/Boothie/portfolio/models.py", line 33, in <module>
class Photo(models.Model):
File "/Users/bli1/Development/Django/Boothie/portfolio/models.py", line 36, in Photo
photo = models.ImageField(upload_to=album.title)
AttributeError: 'ForeignKey' object has no attribute 'title'
I understand the error but I'm not sure how to upload to a directory named with the value of Album.title
.
class Album(models.Model):
title = models.CharField(max_length=50)
# thumbnail = models.ImageField()
def __str__(self):
return self.title
def images(self):
lst = [x.photo.title for x in self.photo_set.all()]
return lst
class Photo(models.Model):
title = models.CharField(max_length=50, blank=True)
album = models.ForeignKey(Album)
photo = models.ImageField(upload_to=album.title)
# width = models.IntegerField(blank=True, null=True)
# height = models.IntegerField(blank=True, null=True)
upload = models.DateTimeField(auto_now_add=True)
# thumbnail = models.ImageField()
Upvotes: 0
Views: 32
Reputation: 258
class Photo(models.Model):
.....
photo = models.ImageField(upload_to=upload_photo_path_function)
.....
def upload_photo_path_function(instance, filename):
path = os.path.join('files/', instance.album.title)
return path
Upvotes: 1