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
我无法摆脱标题中描述的错误。我已经尝试了关于同一主题的其他问题中的建议中的所有内容,但仍然无法正常工作。 最佳答案
您已将数据类型设置为整数
gender = models.**IntegerField**(choices=CHOICE_GENDER)
您的选项以的形式给出字符串
CHOICE_GENDER = (('1', 'Male'), ('2', 'Female'))
而不是“1”应为1
CHOICE_GENDER = ((1, 'Male'), (2, 'Female'))
关于python - ChoiceField : Select a valid choice.这不是可用的选择之一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36396413/