Saturday, December 3, 2016

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

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20161203210418.GY23347%40fattuba.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment