【问题标题】:Can't add a choice form field on custom usercreateform无法在自定义 usercreateform 上添加选择表单字段
【发布时间】:2018-03-10 23:16:46
【问题描述】:

我一直在尝试使用 django 中的扩展用户模型创建自定义注册表单。我一直在尝试添加的自定义字段之一是用户类型,它只能是“员工”或“管理员”。

我的 signUpForm 类看起来像这样

from .models import EMPLOYEE_TYPE_CHOICES 

class SignUpForm(UserCreationForm):
usertype = forms.CharField(
    max_length=10,
    choices=EMPLOYEE_TYPE_CHOICES,
)
userID = forms.CharField(label="User ID")

class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'userID', 'usertype')

EMPLOYEE_TYPE_CHOICES 来自我的 models.py,看起来像这样

EMPLOYEE_TYPE_CHOICES = (
    ('admin', 'Admin'),
    ('employee', 'Employee'),
)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
ADMIN = 'Admin'
EMPLOYEE = 'Employee'
EMPLOYEE_TYPE_CHOICES = (
    (ADMIN, 'Admin'),
    (EMPLOYEE, 'Employee'),
)
usertype = models.CharField(
    max_length=10,
    choices=EMPLOYEE_TYPE_CHOICES,
)
userID = models.CharField(
    max_length=10,
)

运行服务器时,我收到错误 TypeError: init() 得到了一个意外的关键字参数 'choices'

是否有其他方法可以将选项添加到我的表单域?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您的错误来源是由于使用 CharField 而不是使用 ChoiceField。 https://docs.djangoproject.com/en/1.11/ref/forms/fields/#choicefield

    即使您要完成的工作不适用于创建的表单。您必须为您的 Profile 模型创建一个 ModelForm。然后,您可以简单地在模板上呈现该字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多