0

I want to upload photos to different directories. The directory name should have a title from a model class field. I tried this:

image = models.ImageField(upload_to=f"image/posts/{title}")

It created this:

Upload path

I wanted to see the post's title where I get <django.db.models.fields.CharField>.

How can I get the text from this field. To set the text, I used the Django admin panel.

models.py

class Post(models.Model):
    # ...
    title = models.CharField(max_length=250)
    image = models.ImageField(upload_to=f"image/posts/{title}")

For clarification: In my image field, I set the upload address. This address is different for every post. One directory per post. The directory name should be the value of the title field.

1
  • Hello and welcome to Stack Overflow! Please add additional details to highlight exactly what you need. As it's currently written, I find it hard to tell exactly what you're asking. See the how-to-ask page for help clarifying this question. Commented Sep 7, 2018 at 18:02

1 Answer 1

3

In order to get the value of title for the instance of Post to which you are uploading the image, upload_to needs to be a callable. That callable will receive the instance as an argument and you can then get the title.

Something like this:

def post_image_path(instance, filename):
    title = instance.title
    return f"image/posts/{title}/{filename}"

class Post(models.Model):
    # ...
    title = models.CharField(max_length=250)
    image = models.ImageField(upload_to=post_image_path)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.