Warm tip: This article is reproduced from stackoverflow.com, please click
django django-templates

How to get image name in django without extension name

发布于 2020-03-27 10:25:15

How can i get image name without extension name

I'm using this code but output= imagename.jpg .

{{ post.image.name }}

I want like this output=imagename

Questioner
Enes
Viewed
132
Willem Van Onsem 2019-07-03 23:05

You can obtain such name with os.path.splitext [Python-doc] to split a filename in the "root" and the "extension". But you of course do not have access to that in the Django template. But you can define a template filter.

In your app, you can define such template filter, in a file in a module named templatetags, for example ospath.py:

# app/templatetags/ospath.py

from os.path import splitext

from django import template


register = template.Library()

@register.filter
def noext(value):
    return splitext(value)[0]

In your template, you then can load the template tags with {% load ospath %}, and then use the noext template filter:

{% load ospath %}

{{ post.image.name|noext }}

Note however that an extension is just the part after the last dot. Some files have no extension, except if that dot is the first character of the filename. There is no official list of extensions.