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
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.
@Enes: why would it be unsafe? The library itself is not unsafe (it is even a standard library, so it is already available). The
os.path.splitext
, does not make OS calls, it is text processing.@Enes: you can look up the source code here: github.com/python/cpython/blob/master/Lib/ntpath.py#L195