Django不会渲染表单的字段

时间:2015-06-15 16:28:55

标签: django django-models django-forms django-templates django-views

我在models.py中有这个模型:

class Life_events(models.Model):
patient = models.ForeignKey(Demographic)
HSCT_date = models.DateField('HSCT date',null=True,blank=True)
HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True)
partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True)
date_of_input= models.DateField(null=True,blank=True)

def __str__(self):
    return str(self.patient)

我的forms.py包含:

class LifeEventsForm(forms.Form):
def __init__(self, *args, **kwargs):
    super(LifeEventsForm, self).__init__(*args, **kwargs)
    self.helper=FormHelper(self)
    self.helper.field_class = 'col-md-8'
    self.helper.label_class = 'col-md-3'
    self.helper.layout = Layout(
         Fieldset (
            '<b>HSCT</b>',
            Div(
                #HTML(u'<div class="col-md-2"></div>'),
                Div('HSCT_date',css_class='col-md-6'),
                Div('HSCT_outcome',css_class="col-md-6"),
                Div('partaker_in_clinical_trial', css_class='col-md-6'),
                css_class='row',
                ),
         ),

         FormActions(
            Submit('submit', "Save changes"),
            Submit('cancel',"Cancel")
        ),
    )
    self.helper.form_tag = False
    self.helper.form_show_labels = True

class Meta:
    model = Life_events
    exclude = ['patient', 'date_of_input']

我的views.py有:

my_life_ev = LifeEventsForm(prefix='life_ev')
 return render_to_response('input.html', {'frm_life_ev': my_life_ev,}, context)

我的模板文件input.html有:

  {%crispy frm_life_ev%}

当我渲染模板时,我无法看到表单字段,只能看到字段集中的“HSCT”字样。我的html代码根本不包含这些字段。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您的表单继承自forms.ModelForm,它对模型一无所知并忽略Meta类。您应该继承bind()

答案 1 :(得分:0)

您需要声明一个ModelForm。一个简单的表格不会。

class LifeEventsForm(forms.ModelForm)