ePezhman
ePezhman

Reputation: 4010

Django generates form's dropdown very oddly

I have this dropdown with choices which its choices are based on an Enum and form is generated on admin , however 2 of the choices have a weird value and are wrapped by parentheses, I have been using dropdowns like this and it's first time this happening, any idea why this is happening? thanks

my enum:

class ProjectPublicState(object):
    OPEN_FOR_APPLICATIONS = 1
    IN_PROGRESS = 2
    CLOSED = 3,
    NOT_PUBLIC = 4,

    @classmethod
    def default(cls):
        return cls.OPEN_FOR_APPLICATIONS 

in my model:

PUBLIC_STATE_CHOICES = (
        (ProjectPublicState.OPEN_FOR_APPLICATIONS, _('Open for Applications')),
        (ProjectPublicState.IN_PROGRESS, _('In Progress')),
        (ProjectPublicState.CLOSED, _('Closed')),
        (ProjectPublicState.NOT_PUBLIC, _('Not Public')),
    )

and (changing it to models.IntegerField didn't fix it either)

 state_public = FSMIntegerField(
        _('Public State'),
        choices=PUBLIC_STATE_CHOICES,
        default=ProjectPublicState.default()
    )

and the result:

<select name="state_public" id="id_state_public" class="form-control">
<option selected="selected" value="1">Open for Applications</option>
<option value="2">In Progress</option>
<option value="(3,)">Closed</option>
<option value="(4,)">Not Public</option>
</select>

Upvotes: 0

Views: 40

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47906

This is because you have accidentally converted variables CLOSED and NOT_PUBLIC to tuples by putting a comma at the end.

As per Python docs on tuples:

A tuple consists of a number of values separated by commas.

You should remove the trailing comma at the end and it should work fine.

class ProjectPublicState(object):
    OPEN_FOR_APPLICATIONS = 1
    IN_PROGRESS = 2
    CLOSED = 3 # remove the trailing comma
    NOT_PUBLIC = 4 # remove the trailing comma

    @classmethod
    def default(cls):
        return cls.OPEN_FOR_APPLICATIONS 

For example:

In [1]: foo = 1, # assign 'foo' as 1 with a trailing comma at the end

In [2]: foo # print foo
Out[2]: (1,) # a tuple and not just a number 

In [3]: foo = 1,2,3 # Now assign multiple values separated by commas

In [4]: foo
Out[4]: (1, 2, 3) # tuple of 3 elements

Upvotes: 3

Related Questions