2012-03-23 67 views
0

我正在使用Django表单并需要创建一个列表框。列表框Django表格

Django表单字段中的列表框相当于什么?

我查了一下资料@

https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield 

,但无法找到它。

这里是我的代码片段,

Models.py

class Volunteer(models.Model): 
    NO_OF_HRS = (('1','1') 
        ('2','2')) 
    datecreated = models.DateTimeField() 
    volposition = models.CharField(max_length=300) 
    roledesc = models.CharField(max_length=300) 
    Duration = models.CharField(choices=NO_OF_HRS,max_length=1)** 

forms.py

class VolunteerForm(forms.ModelForm) 
    datecreated = forms.DateField(label=u'Creation Date') 
    volposition = forms.CharField(label=u'Position Name', max_length=300) 
    roledesc = forms.roledesc(label=u'Role description',max_length=5000) 
    Duration = forms.CharField(widget=forms.select(choices=NO_OF_HRS),max_length=2) 

当我尝试运行,我收到以下错误,

NO_OF_HRS未定义

回答

1

您的NO_OF_HRS元组在模型中定义,不可用于表单。它必须像其他任何Python对象一样在forms.py中导入。尝试将模型定义和进口外的元组在forms.py这样的:

models.py

NO_OF_HRS = (('1','1') 
      ('2','2')) 

class Volunteer(models.Model): 
    # ... 
    duration = models.CharField(choices=NO_OF_HRS, max_length=1) 

forms.py

from path.to.models import NO_OF_HRS 

class VolunteerForm(forms.Form): 
    # ... 
    duration = forms.CharField(widget=forms.Select(choices=NO_OF_HRS), max_length=1) 

它也像你想使用一个ModelForm。在这种情况下,您不需要将任何字段定义添加到您的VolunteerForm中,只需在内部Meta类中设置您的模型即可。

forms.py

from path.to.models Volunteer 

class VolunteerForm(forms.ModelForm): 
    class Meta: 
     model = Volunteer 
+0

我想你提到什么,但我得到这个错误'module”对象有没有属性‘选择’。 Duration = forms.CharField(widget = forms.select(choices = NO_OF_HRS),max_length = 2) – user1050619 2012-03-24 19:01:19

+0

对不起,从你的代码片段复制粘贴错误。它必须是'forms.Select'(该类以大写字母开头)。另请参阅[完整示例]的文档(https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#a-full-example)。 – 2012-03-24 19:19:42

+0

谢谢..它工作 – user1050619 2012-03-26 19:35:01