AMG
AMG

Reputation: 1646

Convert string into tuple for django choices for forms.Select

I have a string stored in a database as

yes:Yes, I agree;no:No, I do not agree

I am trying to convert that to something I can use as mychoices in the following:

widget=forms.Select(choices=mychoices)

The following works fine if I hardwire in this fashion, but the values are stored as options in the database in a single field (out of my control).

for f in fields:
    # mychoices = f.choices  
    mychoices = (('yes','Yes, I agree'),('no','No, I do not agree'))
    self.fields[f.name] = forms.CharField(label=f.name,
                                            help_text=f.description
                                            widget=forms.Select(choices=mychoices))

I've tried a few variations of split on ; and : but can't seem to find the proper way to do this. I get values errors of needing more than one value to unpack, or having too many values to unpack.

There are records with more than 2 options but all in the format:

code1:Text to display;code2:Text to display;code3:Text to display...

How do I get the f.choices into something like mychoices as hard coded above?

EDIT: Yes using the following worked (thanks @MauroBaraldi - still too new to get you a publicly viewable upvote, but it's there)

for f in fields:
    mychoices = tuple(tuple(c.split(':')) for c in f.choices.split(";"))  
    # mychoices = (('yes','Yes, I agree'),('no','No, I do not agree'))
    self.fields[f.name] = forms.CharField(label=f.name,
                                            help_text=f.description    
                                            widget=forms.Select(choices=mychoices))

Upvotes: 1

Views: 1277

Answers (2)

Mauro Baraldi
Mauro Baraldi

Reputation: 6575

You said that you had problems using split. Perhaps because you've done this way

choices = 'code1:Text to display;code2:Text to display;code3:Text to display'.split(';')

Try this way

choices = 'code1:Text to display;code2:Text to display;code3:Text to display'.split(';')
choices = [c.split(':') for c in choices]

Upvotes: 1

nnaelle
nnaelle

Reputation: 902

You can use Django-model-utils

Upvotes: 0

Related Questions