2

I need to past in template a filename of file which uploaded in instance imagefield.

My class:

def conference_directory_path(instance, filename):
    return 'dialogues/conferences/conference_{0}/avatar/{1}'.format(instance.id, filename)

class Dialogue(models.Model):
    ...
    avatar = models.ImageField(upload_to=conference_directory_path, blank=True)
    ...

Template:

<img src="/static/dialogues/conferences/conference_{{ dialogue.id }}/avatar/{{ dialogue.avatar.filename }}" alt="">

But dialogue.avatar.filename is empty string after rendering. What's wrong? dialogue is an instance of Dialogue model.

Alexander Shpindler
  • 811
  • 1
  • 11
  • 31

1 Answers1

2

What is stored in the database is in fact the filename and not the data. How to access it is described here:

https://docs.djangoproject.com/en/1.10/ref/models/fields/#filefield

All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You’ll most likely want to use the convenience url attribute provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute path to your image in a template with {{ object.mug_shot.url }}.

so we have

<img src="{{ dialogue.avatar.url }}" alt="">
e4c5
  • 52,766
  • 11
  • 101
  • 134