Reputation: 827
I want to access the gallery_path
variable from my create_directory
method as a parameter in my gallery
model field. Is this possible?
class Category(models.Model):
category_title = models.CharField(max_length=200)
category_image = models.ImageField(upload_to="category")
category_description = models.TextField()
slug = models.SlugField(max_length=200, unique=True, default=1)
gallery = models.ImageField(upload_to=gallery_path)
def create_directory(self):
global gallery_path
gallery_path = os.path.abspath(
os.path.join(settings.MEDIA_ROOT, self.slug))
if not os.path.isdir(gallery_path):
os.mkdir(gallery_path)
def save(self, *args, **kwargs):
if not self.pk:
self.create_directory()
super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
shutil.rmtree(os.path.join(settings.MEDIA_ROOT, self.slug))
# os.rmdir(os.path.join(settings.MEDIA_ROOT, self.slug))
super().delete(*args, **kwargs)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.category_title
Thanks for any help
Upvotes: 4
Views: 70
Reputation: 1483
You can't affect image upload path after model loading this way. Models is loaded on application startup, and you're trying to change it after loading.
But you can pass callable to parameter "upload_to" and it will be called every time when new file is being uploaded:
class MyModel(models.Model):
# Need to be defined before the field
def get_image_path(self, filename):
gallery_path = os.path.abspath(
os.path.join(settings.MEDIA_ROOT, self.slug))
if not os.path.isdir(gallery_path):
os.mkdir(gallery_path)
return os.path.join(gallery_path, filename)
gallery = models.ImageField(upload_to=get_image_path)
Documentation: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to
Upvotes: 1