2012-03-23 27 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