2

I want to apply css style(link is below) to my Django boolean form in my template. https://proto.io/freebies/onoff/

I did something like this. The style is applied to the checkbox but the checkbox doesn't change status 'OFF' to 'ON'. (when I click it, it would not do anything)

Template
<div class="onoffswitch">
  <span class="onoffswitch-checkbox" id="myonoffswitch" checked>{{form.mixed_load}}</span>
    <label class="onoffswitch-label" for="myonoffswitch">
       <span class="onoffswitch-inner"></span>
       <span class="onoffswitch-switch"></span>
    </label>
</div>

Forms.py
mixed_load = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'onoffswitch'}))

Can someone tell me how to apply css style to Django form more effectively?

Thank you

smchae
  • 1,035
  • 3
  • 17
  • 39
  • Why aren't you using a CSS framework like Bootstrap, Foundation, Semantic UI etc. It will lessen a lot of your UI work. – Rafiqul Hasan Aug 10 '16 at 13:27

1 Answers1

3

You need to replace your code to look like this in your forms.py:

mixed_load = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'onoffswitch','id': 'myonoffswitch'}))

You were missing id attribute, which is used in the for attribute of label tag. See this answer for in-depth explanation what is the for tag for, and why do you need to set id on your input field.

However I can recommend you using django-widget-tweaks, which is really nice and easy to use.

Full working code:

Make sure you have css styles applied to the template file.

# template
...
<div class="onoffswitch">
    {{ form.mixed_load }}
    <label class="onoffswitch-label" for="myonoffswitch">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div>
...

# forms.py
mixed_load = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'onoffswitch-checkbox','id': 'myonoffswitch'}))

This way is one of proposed ways to customize widget look.

Community
  • 1
  • 1
an0o0nym
  • 1,456
  • 16
  • 33
  • I changed my code and it is not still working. Is the code above a right way to use div class with {{form.mixed_load}}? And if I use django-widget-tweaks, where do I place my div class? If you could tell me how to use widget-tweaks(i.e. where and how to place div class ?) – smchae Aug 10 '16 at 04:48
  • @smchae Your question regards the problem of making the checkbox work properly. I reconstructed your problem and I made it work with the posted code example. The question you are asking in your comment should be posted as a separate new question. Additionally, the first line of `django-widget-tweaks` github page(see link in my answer),says 'Tweak the form field rendering in templates...'. So you cannot use it to add custom classes to your divs. You need to do that statically as you did originally. – an0o0nym Aug 10 '16 at 14:36
  • Thank you so much. Your answer and comment are so helpful! – smchae Aug 11 '16 at 00:48