Skip to content

Instantly share code, notes, and snippets.

@linxuedong
Forked from eezis/crispy-forms-inlineradios.py
Last active January 5, 2018 04:07
Show Gist options
  • Save linxuedong/e559b437a0b7d4dd6f6cd8a6d1a26e77 to your computer and use it in GitHub Desktop.
Save linxuedong/e559b437a0b7d4dd6f6cd8a6d1a26e77 to your computer and use it in GitHub Desktop.
Horizontal Radio Buttons For Boolean Values Using Crispy Forms with Django
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
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')),
)
@linxuedong
Copy link
Author

@linxuedong
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment