django 如何创建一个表单choiceField与选择模型TextChoices?

r8xiu3jd  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(230)

我有一个带有一些文本选项的自定义用户模型,如何将该选项“大陆”放入表单?以便我使用{{ form }}渲染html页面并显示选项?
我试过Forms1.py和Forms2.py,但都不起作用。
Models.py

class CustomUser(AbstractUser): #USER MODEL
    
    # CHOICES FOR USER CONTINENT
    class Continents(models.TextChoices):
        EUROPE = 'EUROPE' , 'EUROPE'
        AFRICA = 'AFRICA' , 'AFRICA'
        SOUTH_AMERICA = 'SOUTH AMERICA' , 'SOUTH AMERICA'
        NORTH_AMERICA = 'NORTH AMERICA' , 'NORTH AMERICA'
        OCEANIA = 'OCEANIA' , 'OCEANIA'
        ASIA = 'ASIA' , 'ASIA'
        
    username=None 

    nickname = models.CharField(max_length= 50, default = 'Not Set', blank=True)
    bio = models.TextField(max_length = 500 , blank=True , null= True , default= "Not Set")

    email = models.EmailField(max_length= 256 , unique=True) #USERS EMAIL ADDRESS

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

Forms1.py

class CompleteProfileForm(forms.Form):

    bio = forms.CharField(
        label='Bio: ',
        widget = forms.Textarea(
            attrs = {
                'class':'bioInput'
            }
        )

    )
    class Meta:
        model = CustomUser
        fields = ['bio', 'continent']
        exclude = ['username']
        continents = forms.ChoiceField(label='Continents', choices= CustomUser.Continents)

Forms2.py

class CompleteProfileForm(forms.Form):

    bio = forms.CharField(
        label='Bio: ',
        widget = forms.Textarea(
            attrs = {
                'class':'bioInput'
            }
        )

    )
    continents = forms.ChoiceField(
         choices=CustomUser.Continents,
         widget = forms.Select(
             attrs = {
                'class':'continent',
                'selected':'Continent',
                'id':'continent',
            } 
      )
    )

我也用UserCreationForm完成了这一点,它是这样工作的,对于字段性别:
Forms.py

class CustomUserCreationForm(UserCreationForm):

    

    ......
    ......
    ......

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ['email', 'password1', 'password2', 'gender']
        exclude = ['username']
        genders = forms.ChoiceField(label = 'Gender: ', choices= CustomUser.Genders)

i获取的错误为:TypeError: EnumType.__call__() missing 1 required positional argument: 'value'

yhxst69z

yhxst69z1#

Django作为你找到的一个内置的form.ChoiceField(doc)。
您忽略的是choices=参数接受一个列表,该列表是一个表示选项的元组。该列表可以通过.choices字段(doc)从TextChoices中检索

continents = forms.ChoiceField(
    choices=CustomUser.Continents.choices,
)

上面的方法应该可以

相关问题