Skip to content

Instantly share code, notes, and snippets.

@krzysztofjeziorny
Last active September 9, 2020 18:57
Show Gist options
  • Save krzysztofjeziorny/1796792bc425df886a2299c2b0371698 to your computer and use it in GitHub Desktop.
Save krzysztofjeziorny/1796792bc425df886a2299c2b0371698 to your computer and use it in GitHub Desktop.
custom django form widgets (toggle)
# forms.py
from django import forms
from . import widgets
class CustomWidgetForm(forms.Form):
working = forms.BooleanField(
required=False,
widget=widgets.ToggleWidget(
options={
'on': 'Yep',
'off': 'Nope'
}
)
)
# views.py
from django.shortcuts import render
from .forms import CustomWidgetForm
def home(request):
if request.GET:
form = CustomWidgetForm(request.GET)
else:
form = CustomWidgetForm()
context = {
'form': form
}
return render(
request,
'home.html',
context
)
# widgets.py
from django import forms
class ToggleWidget(forms.widgets.CheckboxInput):
class Media:
css = {'all': (
"https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css", )}
js = ("https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js",)
def __init__(self, attrs=None, *args, **kwargs):
attrs = attrs or {}
default_options = {
'toggle': 'toggle',
'offstyle': 'danger'
}
options = kwargs.get('options', {})
default_options.update(options)
for key, val in default_options.items():
attrs['data-' + key] = val
super().__init__(attrs)
# Source: https://blog.ihfazh.com/django-custom-widget-with-3-examples.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment