我尝试在我的表单中创建单选按钮和复选框,并尝试分别使用模型字段ChoiceField
和MultipleChoiceField
。
forms.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)")
models.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'
我的代码似乎有什么问题?
答案 0 :(得分:4)
模型定义数据库级别类型。
您必须指定模型的数据类型,并且可以使用“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有选择的模型
答案 1 :(得分:2)
您应该使用 models.CharField :-) see documentation
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)