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?
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:
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
imgtag:<img src="{{ c.cover.url }}"alt="cover image for {{ c.name }}"
/>
You can also get some other benefits, for example:
Now you can do:
<img src="{{ c.cover.url }}" height="{{ c.cover_height }}" width="{{ c.cover_width }}">