django 1.5 – How to use variables inside static tag

You should be able to concatenate strings with the add template filter: {% with ‘assets/flags/’|add:request.LANGUAGE_CODE|add:’.gif’ as image_static %} {% static image_static %} {% endwith %} What you are trying to do doesn’t work with the static template tag because it takes either a string or a variable only: {% static “myapp/css/base.css” %} {% static variable_with_path … Read more

How to add url parameters to Django template url tag?

First you need to prepare your url to accept the param in the regex: (urls.py) url(r’^panel/person/(?P<person_id>[0-9]+)$’, ‘apps.panel.views.person_form’, name=”panel_person_form”), So you use this in your template: {% url ‘panel_person_form’ person_id=item.id %} If you have more than one param, you can change your regex and modify the template using the following: {% url ‘panel_person_form’ person_id=item.id group_id=3 %}

Django – Simple custom template tag example

Here is my solution (based on a custom tag): Firstly create the file structure. Go into the app directory where the tag is needed, and add these files: templatetags templatetags/__init__.py templatetags/video_tags.py The templatetags/video_tags.py file: from django import template register = template.Library() @register.simple_tag def get_rate(crit, rates): return rates.get(crit=crit).rate The template part, with our tag call: {% … Read more

How do I include image files in Django templates?

Try this, settings.py # typically, os.path.join(os.path.dirname(__file__), ‘media’) MEDIA_ROOT = ‘<your_path>/media’ MEDIA_URL = ‘/media/’ urls.py urlpatterns = patterns(”, (r’^media/(?P<path>.*)$’, ‘django.views.static.serve’, {‘document_root’: settings.MEDIA_ROOT}), ) .html <img src=”https://stackoverflow.com/questions/901551/{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>” /> Caveat Beware! using Context() will yield you an empty value for {{MEDIA_URL}}. You must use RequestContext(), instead. I hope, this will help.

Need to convert a string to int in a django template

you can coerce a str to an int using the add filter {% for item in numItems|add:”0″ %} https://docs.djangoproject.com/en/dev/ref/templates/builtins/#add to coerce int to str just use slugify {{ some_int|slugify }} EDIT: that said, I agree with the others that normally you should do this in the view – use these tricks only when the alternatives … Read more

Applying bootstrap styles to django forms

If you prefer not to use 3rd party tools then essentially you need to add attributes to your classes, I prefer to do this by having a base class that my model forms inherit from class BootstrapModelForm(ModelForm): def __init__(self, *args, **kwargs): super(BootstrapModelForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ ‘class’: ‘form-control’ }) Can easily be … Read more