Django 形式的性
Posted
技术标签:
【中文标题】Django 形式的性【英文标题】:Django forms for sex 【发布时间】:2021-08-11 15:29:03 【问题描述】:我正在使用将性别存储为 0 - 男性和 1 - 女性的数据库。
我的 forms.py 看起来像这样
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = TbUser
def clean_username(self):
username = self.cleaned_data["username"]
try:
TbUser.objects.get(username=username)
except TbUser.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
class TbUserRegisterForm(CustomUserCreationForm):
email = forms.EmailField()
class Meta:
model = TbUser
fields = ['username', 'email', 'cellphone', 'sex', 'role', 'department', 'password1', 'password2']
Django 用户模型
class TbUser(AbstractBaseUser, PermissionsMixin):
id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4)
username = models.CharField(max_length=40, blank=True, null=True, unique=True, db_column='usname')
password = models.CharField(max_length=255, blank=True, null=True, db_column='dj_psword')
email = models.CharField(max_length=255, blank=True, null=True)
cellphone = models.CharField(max_length=100, blank=True, null=True)
image_id = models.CharField(max_length=40, blank=True, null=True)
sex = models.IntegerField(blank=True, null=True)
is_available = models.IntegerField(blank=True, null=True)
role = models.ForeignKey(TbRole, on_delete=models.CASCADE)
department = models.ForeignKey(TbDepartment, on_delete=models.CASCADE)
is_superuser = models.BooleanField(default=False, blank=True, null=True, db_column='default_super')
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = TbUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
managed = False
db_table = 'tb_user'
def __str__(self):
return '%s' % self.username
由于sex 是一个整数字段,UI 表单字段不是一个选择字段,而只是显示用于递增整数的箭头。有没有办法让它成为 m 将存储 0 和 f - 1 的选择字段?
【问题讨论】:
【参考方案1】:是的,您可以将此分配给choices=…
parameter [Django-doc]:
SEX_CHOICES = [
(0, 'Male')
, (1, 'Female')
]
class TbUser(AbstractBaseUser, PermissionsMixin):
# …
sex = models.IntegerField(blank=True, null=True, choices=SEX_CHOICES)
# …
【讨论】:
以上是关于Django 形式的性的主要内容,如果未能解决你的问题,请参考以下文章