python – ChoiceField:选择一个有效的选择.这不是可用的选择之一

models.py:

from django.db import models
from django.contrib.auth.models import User as BaseUser

CHOICE_GENDER = ((1, 'Male'), (2, 'Female'))


class Location(models.Model):
    city = models.CharField(max_length=75)
    country = models.CharField(max_length=25)

    def __unicode__(self):
        return ', '.join([self.city, self.state])


class Users(BaseUser):
    user = models.OneToOneField(BaseUser, on_delete=models.CASCADE)
    gender = models.IntegerField(choices=CHOICE_GENDER)
    birth = models.DateField()
    location = models.ForeignKey(Location)

    class Meta:
        ordering = ('user',)

forms.py:

from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import Users, Location, CHOICE_GENDER


class LocationForm(forms.ModelForm):
    city = forms.CharField(max_length=75)
    country = forms.CharField(max_length=25)

    class Meta:
        model = Location
        fields = ('city', 'country',)


class RegistrationForm(UserCreationForm):
    email = forms.CharField(max_length=75)
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    gender = forms.ChoiceField(choices=CHOICE_GENDER)
    birth = forms.DateField()
    location = LocationForm()

    class Meta:
        model = Users
        fields = ('username', 'email', 'first_name', 'last_name', 'gender', 'birth',)

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.gender = self.cleaned_data['gender']
        user.birth = self.cleaned_data['birth']
        loc = LocationForm(city=self.cleaned_data['city'], country=self.cleaned_data['country'])
        user.location = loc
        if commit:
            user.save()
        return user

我无法克服标题中描述的错误.我已经尝试过关于同一主题的其他问题的建议,但它仍然无效.有人可以帮我弄这个吗?提前致谢!

最佳答案
您已将数据类型设置为Integer

gender = models.**IntegerField**(choices=CHOICE_GENDER)

你的选择以字符串形式给出

CHOICE_GENDER = (('1', 'Male'), ('2', 'Female'))

而不是’1’应该是1

CHOICE_GENDER = ((1, 'Male'), (2, 'Female'))

转载注明原文:python – ChoiceField:选择一个有效的选择.这不是可用的选择之一 - 代码日志