-
-
Save linxuedong/e559b437a0b7d4dd6f6cd8a6d1a26e77 to your computer and use it in GitHub Desktop.
Horizontal Radio Buttons For Boolean Values Using Crispy Forms with Django
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
Quick guide to getting inlineradio buttons when using boolean values with Crispy Forms. | |
1. create chocies | |
BOOLEAN_YN = ( | |
(True, u'Yes'), | |
(False, u'No'), | |
) | |
2. update model to point at the choices | |
under_maintenance_now = models.BooleanField(default=False, choices=BOOLEAN_YN) | |
3. Update the Field in the forms.py ModelForm (import it first) | |
from crispy_forms.bootstrap import InlineRadios | |
Div(InlineRadios('under_maintenance_now'), css_class="col-md-3"), | |
That's it, no need to mess with the widgets |
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
class PaperForm(forms.ModelForm): | |
score = forms.TypedChoiceField( | |
label="Score", | |
choices=((100, "A"), (80, "B"), (60, "C"), (0, "D")), | |
coerce=lambda x: int(x), | |
widget=forms.RadioSelect, | |
required=True, | |
) | |
class Meta: | |
model = Paper | |
fields = ['score', 'status'] | |
widgets = {'status': forms.HiddenInput()} | |
def __init__(self, *args, **kwargs): | |
super(PaperForm, self).__init__(*args, **kwargs) | |
self.initial['status'] = '1' | |
self.fields['score'].required = True | |
self.helper = FormHelper() | |
self.helper.form_id = 'PaperForm' | |
self.helper.form_class = 'paper-form' | |
self.helper.add_input(Submit('submit', 'Submit')) | |
self.helper.layout = Layout( | |
Div(InlineRadios('score')), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Layouts — django-crispy-forms 1.0.0 documentation