Last active
September 9, 2020 18:57
-
-
Save krzysztofjeziorny/1796792bc425df886a2299c2b0371698 to your computer and use it in GitHub Desktop.
custom django form widgets (toggle)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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' | |
} | |
) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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