Deadly
Deadly

Reputation: 2094

ImageField: save filename only

I have model with ImageFile field:

def upload_course_cover(object, filename):
    return '/media/courses/%s_%s' % (Course.objects.aggregate(Max('id'))['id__max'] + 1, filename)

class Course(models.Model):
    # ...
    cover = models.ImageField(upload_to=upload_course_cover,  blank=True)

When the image is saved, into cover field will be writen full image path /media/courses/id_filename.ext, but I want store only image name id_filename.ext. How to do it?

Upvotes: 1

Views: 3027

Answers (2)

Aloo Gobi
Aloo Gobi

Reputation: 176

"When the image is saved, into cover field will be writen full image path /media/courses/id_filename.ext"

To be precise, this is not true. Only the relative path from your MEDIA_ROOT is saved in the database. See https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to

(ImageField has the same properties as FileField)

To save only the filenames, you could

  1. Add a new CharField to store the names
  2. Use os.split() to get just the filename when called

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174624

You cannot change what it stores in the database - unless you create your own custom field; or use a CharField.

If you just want to display the filename:

import os
c = Course.objects.get(pk=1)
fname = os.path.basename(c.cover.name)

# if cover's name is /hello/foo/bar.html
# fname will be bar.html

However, since you have image field - you can get lots of benefits out of it, for example - to get the URL to display the image in an img tag:

<img src="{{ c.cover.url }}" alt="cover image for {{ c.name }}" />

You can also get some other benefits, for example:

class Course(models.Model):
    # ....
    cover_height = models.IntegerField()
    cover_width = models.IntegerField()

    cover = models.ImageField(upload_to=upload_course_cover,
                              height_field=cover_height,
                              width_field=cover_width,
                              # your other options...
                              )

Now you can do:

<img src="{{ c.cover.url }}" height="{{ c.cover_height }}" width="{{ c.cover_width }}">

Upvotes: 3

Related Questions