Dave_750
Dave_750

Reputation: 1245

Django Admin Radio Buttons

Looking for a way to use radio buttons in the Django admin. I would like to have 3 or 4 hard coded options the user can select from and I will use that selection to know what to do with the next text field. The options never need to change. Can anyone point me in the right direction? Google is not cooperating on this one...

Upvotes: 0

Views: 2731

Answers (1)

DavidM
DavidM

Reputation: 1437

I'm going to assume you want this on the change page for a Foo model object. Let's call the extra field my_option.

First, you'll need to use a custom form in your FooAdmin class so you can get the extra field in there:

class FooAdmin:
    ...
    form FooForm
    fields = (..., 'my_option', ...)
    ...

Then, just create the form with the extra option:

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo
    my_option = ChoiceField(
        label = 'Options',
        choices = (
            (0, 'Don\'t change anything.'),
            (1, 'Do some crazy stuff.'),
            (2, 'Do other stuff.'),
        ),
        initial = 0,
        widget = RadioSelect,
    )

ChoiceField defaults to using a select box, which is why you also need to override the widget type in the field's constructor. You can also check out TypedChoiceField if that serves your needs better.

Finally, you'll need to handle the field somewhere. I suggest overriding the clean() method in FooForm to get the value and set values in self.cleaned_data depending on what you want the option to do.

Upvotes: 2

Related Questions