1

我正在尝试在管理员中为我的用户设置性别但得到错误

Value u"[u'm']" is not a valid choice.

管理员.py

class PlayerForm(forms.ModelForm):
    GENDER_CHOICES = (
        ('m', 'Male'),
        ('f', 'Female'),
    )
...
gender = forms.MultipleChoiceField(label="Gender", choices=GENDER_CHOICES)
...

class Meta:
    model = Player


class PlayerAdmin(admin.ModelAdmin):
    form = PlayerForm


admin.site.register(Player, PlayerAdmin)

models.py(玩家模型)

class Player(AbstractBaseUser):
    GENDER_CHOICES = (
        ('m', 'Male'),
        ('f', 'Female'),
    )
    ...
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    ...

有趣的事实:表单确实在管理员中显示了来自数据库的正确默认值。

尝试提交表单时的 POST Payload:

------WebKitFormBoundary009tVyo4cRJvIAnC
Content-Disposition: form-data; name="gender"

m

编辑:忘了提到数据库是 Postgres 8.4 并且有问题的列是

VARCHAR(1)
4

1 回答 1

1

由于您使用的是MultipleChoiceField

gender = forms.MultipleChoiceField(label="Gender", choices=GENDER_CHOICES)

它将性别保存到“列表”中。导致:

>>> gender = ['m']

您需要使用ChoiceFieldwhich 用于选择单个事物:

gender = forms.ChoiceField(label="Gender", choices=GENDER_CHOICES)

导致:

>>> gender = 'm'
于 2013-02-23T14:37:27.217 回答