Skip to main content
 首页 » 编程设计

python之Django: 'module' 对象没有属性 'ChoiceField' , 'MultipleChoiceField'

2025年05月04日33txw1958

我正在尝试在我的表单中创建单选按钮和复选框,并尝试分别使用模型字段 ChoiceField 和 MultipleChoiceField 来实现相同的目的。

表单.py

from django import forms 
from rango.models import Evangelized 
 
class EvangelizedForm(forms.ModelForm): 
    gender = forms.ChoiceField(widget=forms.RadioSelect( 
                 choices=Evangelized.GENDER_CHOICES), help_text="Gender") 
    area_of_interest = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple( 
                                                    choices=Evangelized.AREA_CHOICES), help_text="Areas of interest(Upto 3)") 

模型.py

from django.db import models 
 
class Evangelized(models.Model): 
    GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'), ('U', 'Unisex/Parody')) 
    gender = models.ChoiceField(choices=GENDER_CHOICES) 
    AREA_CHOICES = (('Govt', 'Govt'), ('Entertainment', 'Entertainment'), ('Automobile', 'Automobile'), 
                        ('Careers', 'Careers'), ('Books', 'Books'), ('Family', 'Family'), ('Food', 'Food'), 
                            ('Gaming', 'Gaming'), ('Beauty', 'Beauty'), ('Sports', 'Sports'), ('Events', 'Events'), 
                                ('Business', 'Business'), ('Travel', 'Travel'), ('Health', 'Health'), ('Technology','Technology')) 
    area_of_interest = models.MultipleChoiceField(choices=AREA_CHOICES) 

但是,我在分别处理每种类型的模型字段时遇到以下错误:

 'module' object has no attribute 'ChoiceField' 
 
 
 
'module' object has no attribute 'MultipleChoiceField' 

我的代码似乎有什么问题?

请您参考如下方法:

模型定义了数据库级别的类型。

您必须指定模型的数据类型,并且可以使用“choices”kwarg 指定选项。

因此,您的模型应如下所示:

from django.db import models 
 
class Evangelized(models.Model): 
    GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'), ('U', 'Unisex/Parody')) 
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES) 

对于多选字段的情况,您可以使用 CommaSeparatedIntegerField .

我建议你看看 docs对于有选择的模型