forest
forest

Reputation: 1464

Django: How do I upload an image to a folder named after the article slug

I defined two models Article, Article_photos. Photos present in each article is stored in the relevant Article_photos model. I intend to store multiple photos per article in this way. I want each photo to be uploaded to a folder by naming the folder in this manner: {slug}_images.

This is Article model:

class Article(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='Author')
    article_title = models.TextField()
    article_content = models.TextField()
    slug = models.SlugField(max_length=30, blank=True)
    ...

    def save(self, *args, **kwargs):
        self.slug = slugify(self.article_title)
        super(Article, self).save(*args, **kwargs)

And the Article_photos model to store one or more photos:

class Article_photo(models.Model):
    article = models.ForeignKey('Article', on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='{}_images'.format(article.slug))

Now, when i'm running makemigrations, it's returning this error: AttributeError: 'ForeignKey' object has no attribute 'slug'.

How do rename the folder in the pattern I want?

Upvotes: 2

Views: 437

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You need to make use of a function here, for example:

def article_photo_location(self, filename):
    return '{}_images/{}'.format(self.article.slug, filename)

class Article_photo(models.Model):
    article = models.ForeignKey('Article', on_delete=models.CASCADE)
    photo = models.ImageField(upload_to=article_photo_location)

Note that you should not call the function, you pass a reference of the function to the upload_to=… parameter [Django-doc].

Note: normally a Django models, just like all classes in Python are given a name in PerlCase, not snake_case, so it should be: ArticlePhoto instead of Article_photo.

Upvotes: 4

Related Questions