A simple django basename template filter tag
I'm using Django, a python coded framework to develop web applications, to implement a project for the University.
During the development I needed to have a template tag which, given a path to a file, just returns its basename (just as it do the python os.path.basename).
So I implemented it. Following you have the code for it.
from django import template
from django.template.defaultfilters import stringfilter
import os
register = template.Library()
@register.filter(name='basename')
@stringfilter
def basename(value):
return os.path.basename(value)
In order to use this tag just:
- copy the above code into a file called mytags.py under a directory called templatetags just in the same level of your manage.py file in your application root.
- create an empty __init__.py file in the templatetags directory (so that python knows this is a package)
- in your template just after the {% extends .. %} tags insert the {% load mytags %} tag.
- use your new filter to get filenames from a full file path:
{{ render.media_file|basename }}
Note: The above filter will work also on URLs but only on *nix system as os.path.basename will expect a \ under windows. The filter code should be modified and made more complex to support URLs under windows.. but this is out of my needs now. Post a comment if you implement it or if you just have ideas.
For more informations read Django's documentation on writing custom templates tags and filters.



Django - Embed videos on unbuntu host
I visited this page to learn how to use django to create the magic needed to show embedded videos,, eg as at [http://excess.org/article/2009/06/django-1-1-talk-video/], but I am probably missing some basic reference to how to do this, with examples.
Actually, once you understand
Actually, once you understand how django works, writing some templates to embed videos wont be hard. It's just a matter of putting everything together.
You might wanna have a look at djvideo, a django templatetag library to embed video.
Hope this helps, ask for more help if you need it.
Serious typo in your code
Hi your code saved me some time. At the same time it also cost me half an hour trying to debug why it kept saying
The problem is that there is a typo in your source code. It should say
instead of
I'm sorry for the error.
I'm sorry for the error. Fixed that. thanks for reporting it.
Post new comment