Hassan Baig
Hassan Baig

Reputation: 15844

Alternative ways of styling class-based form fields

In Django, one applies CSS styling to class-based form fields in forms.py (or equivalent).

My question: is it impossible to do it any other way inside a Django project?


I'll accept the answer even if the answer is "it's impossible". Hacks and tricks are acceptable as well. Illustrative examples would be great.

p.s. here's an example of a Django form where I've styled in the class-based form:

class SampleForm(forms.Form):
    description = forms.CharField(max_length=250)

    def __init__(self,*args,**kwargs):
        super(SampleForm, self).__init__(*args,**kwargs)
        self.fields['description'].widget.attrs['class'] = 'btn bcg'
        self.fields['description'].widget.attrs['style'] = 'background-color:#F8F8F8; width:98%; color: #1f8cad;'
        self.fields['description'].widget.attrs['autocomplete'] = 'off'

Upvotes: 1

Views: 56

Answers (1)

Sascha Rau
Sascha Rau

Reputation: 357

You can use template tags.

css.py

from django import template
register = template.Library()

@register.filter(name='css')
def css(field, css):
    return field.as_widget(attrs={"style":css})

in your template:

{% load css %}
{{ item.field|css: 'width: 100px' }}

the result could be

<input id="id_field" name="field" style="width: 100px" type="text" />

As you can see, in style is your variable (width: 100px). You can also do it with class.

Upvotes: 1

Related Questions