Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to render radio #1980

Open
bluefishers opened this issue May 1, 2020 · 2 comments
Open

how to render radio #1980

bluefishers opened this issue May 1, 2020 · 2 comments

Comments

@bluefishers
Copy link

bluefishers commented May 1, 2020

default, create or edit boolean field in form will render to checkbox,
if I want to render to radio,how to do it?

@kataev
Copy link

kataev commented Jun 4, 2020

This is easy with wtfforms

import enum

from wtforms import RadioField
from markupsafe import Markup
from flask_admin.form import BaseForm


class BootstrapRadioFieldWidget:
    def __init__(self, inline: bool = False, prefix_label: bool = True):
        self.inline = inline
        self.prefix_label = prefix_label

    def __call__(self, field: RadioField, **kwargs: typing.Any) -> HTMLString:
        kwargs.setdefault('id', field.id)
        html = []
        if self.inline:
            template = '<label class="radio-inline">%s %s</label>'
        else:
            template = '<div class="radio"><label>%s %s</label></div>'
        for subfield in field:
            if self.prefix_label:
                html.append(template % (subfield.label, subfield()))
            else:
                html.append(template % (subfield(), subfield.label))
        return Markup(''.join(html))


class BootstrapRadioField(RadioField):
    widget = BootstrapRadioFieldWidget(prefix_label=False)


class SomeEnum(str, enum.Enum):
    first = 'one'
    second = 'two'

class SearchForm(BaseForm):
    type = BootstrapRadioField(
        'Choice', choices=[(i.name, i.value) for i in list(SomeEnum)], default=SomeEnum.value.name,
    )

Now use SearchForm in custom view, or integrate BootstrapRadioField in your generated modelform.

@bluefishers
Copy link
Author

thank you!but how to integrate BootstrapRadioField in the generated modelform,can you show the example code.

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

No branches or pull requests

2 participants