2011-05-06 134 views

回答

7

你想用ChoiceFieldRadioSelect

from django import forms 

class GenderForm(forms.Form): 
    CHOICES = (
     ('M', 'Male'), 
     ('F', 'Female'), 
    ) 
    choice = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) 

記住,Django documentation is your friend

動態改變選擇 如果你希望能夠動態地創建形式,它可能是使用的ModelForm,而不是forms.Form一個好主意。這裏有一個例子:

from django.db import models 
from django.forms import ModelForm 
from django import forms 

class Answer(models.Model): 
    answer = models.CharField(max_length=100) 

    def __unicode__(self): 
     return self.answer 

class Question(models.Model): 
    title = models.CharField(max_length=100) 
    answers = models.ManyToManyField('Answer') 

class QuestionForm(ModelForm): 
    class Meta: 
     model = Question 
     fields = ('title', 'answers') 
     widgets = { 
      'answers': forms.RadioSelect(), 
     } 

在你看來實例與指定使用實例的形式:

question = Question.objects.order_by('?')[0] 
form = QuestionForm(instance=question) 

的形式,然後將使用與該問題有關的答案(在這種情況下,隨機選擇)和像往常一樣將表單傳遞給模板上下文。

+0

如何讓它動態改變每個問題的選擇? – 2011-05-06 09:07:57

3

有一個很好的例子,如何在這裏做到這一點:https://code.djangoproject.com/wiki/CookBookNewFormsDynamicFields

基本上,你的表單代碼將遵循這個模式:

from django import forms 

class MyForm(forms.Form): 
    static_field_a = forms.CharField(max_length=32) 
    static_field_b = forms.CharField(max_length=32) 
    static_field_c = forms.CharField(max_length=32) 

    def __init__(self, dynamic_field_names, *args, **kwargs): 
     super(MyForm, self).__init__(*args, **kwargs) 

     for field_name in dynamic_field_names: 
      self.fields[field_name] = forms.CharField(max_legth=32) # creates a dynamic field 

用法示例:

>>> dynamic_fields = ('first_name', 'last_name', 'company', 'title') 
>>> my_form = MyForm(dynamic_field_names=dynamic_fields) 
>>> my_form.as_ul() 
u'<li><label for="id_static_field_a">Static field a:</label> <input id="id_static_field_a" type="text" name="static_field_a" maxlength="32" /></li>\n<li><label for="id_static_field_b">Static field b:</label> <input id="id_static_field_b" type="text" name="static_field_b" maxlength="32" /></li>\n<li><label for="id_static_field_c">Static field c:</label> <input id="id_static_field_c" type="text" name="static_field_c" maxlength="32" /></li>\n<li><label for="id_first_name">First name:</label> <input id="id_first_name" type="text" name="first_name" maxlength="32" /></li>\n<li><label for="id_last_name">Last name:</label> <input id="id_last_name" type="text" name="last_name" maxlength="32" /></li>\n<li><label for="id_company">Company:</label> <input id="id_company" type="text" name="company" maxlength="32" /></li>\n<li><label for="id_title">Title:</label> <input id="id_title" type="text" name="title" maxlength="32" /></li> 

那將呈現帶有以下文本輸入的表單:

  • 靜態字段
  • 靜態字段B
  • 靜態的字段c
  • 公司
  • 標題

只需使用forms.ChoiceField(),或任何你想要的,而不是forms.TextField()

+0

不錯,但下次我會用更具體的例子。使用無意義的變量名很難跟蹤代碼。 – 2012-04-29 08:06:00