I'm outputting fields of a form in a template like this {{ form.first_name }}
and I'd like to add a class (eg. blueprint's span-x-class) to it. So I'd like to know if there's a nice readymade solution (template filter) for that, which I could use in the fashion {{ form.first_name|add_class:"span-4" }}
? (I just want to know if Django's developers or anybody has thought of that yet without my knowledge before doing it on my own)
The static folder should be created in your project folder, that's where you can create in static folder a folder called css, and then in the css folder add the css files.
{{ form. as_p }} – Render Django Forms as paragraph.
You only need to install Django widget_tweaks
pip install django-widget-tweaks
After you can to do something like that on your template:
{{ form.search_query|attr:"type:search" }}
--
Read all about it here.
To solve this I made my own template filter, you can apply it on any tag, not just input elements!
class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.filter
def add_class(value, css_class):
string = unicode(value)
match = class_re.search(string)
if match:
m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class,
css_class, css_class),
match.group(1))
print match.group(1)
if not m:
return mark_safe(class_re.sub(match.group(1) + " " + css_class,
string))
else:
return mark_safe(string.replace('>', ' class="%s">' % css_class))
return value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With