Re: Best practice for implementing a dynamic "other" field in a group of radio buttons?

8 views
Skip to first unread message

Ryan Nowakowski

unread,
Dec 3, 2016, 4:04:45 PM12/3/16
to django...@googlegroups.com
On Fri, Nov 25, 2016 at 03:47:45PM -0800, Quentin Fulsher wrote:
> Hi all,
>
> I'm working on a form that has to support a few groups of radio buttons.
> I'm wondering if there is a recommended way to do an "other" radio button
> that can be dynamically set by the user. Like the user can select the
> "other" radio button and enter a custom string to be associated with their
> "other" selection. My model is set up like this:
>
> GENDER_CHOICES = (
> ('M', 'Man'),
> ('W', 'Woman'),
> ('N', 'Prefer not to answer'),
> ('O', 'Other'),
> )
> gender = models.CharField(
> max_length=1,
> choices=GENDER_CHOICES,
> default='',
> blank=True
> )
>
>
> This is good but I would like for the user to be able to define what string
> the "O" choice points to. Kinda like this from a google doc:
>
> <https://lh3.googleusercontent.com/-wc4dNjH7Zkw/WDjMgbyhabI/AAAAAAAAA0Q/ydfXuNSf1ekzog5MgRzZTRtQDcBPBpPbQCLcB/s1600/form-ex.png>
>
> Is there an easy way to do this with django forms?

First, you'll need another model field to store the "custom" gender
string:

custom_gender = models.CharField(max_length=100, default='', blank=True)

Then, implement the model.clean method:

def clean(self):
if self.gender == 'O' and self.custom_gender == '':
raise ValidationError({'custom_gender': "Please enter your other gender"})

Note that you could implement the clean method on the form instead of
the model. However if this is a hard and fast rule everywhere including
in the django admin, I'd implement it in the model.

- Ryan
Reply all
Reply to author
Forward
0 new messages