在django表单中使用实例变量

时间:2014-05-08 08:11:29

标签: django django-forms

我在我的视图中使用模型实例初始化表单,如此

entry_form = EntryDetailsForm(instance=entry)

我的模型表格如下

class EntryDetailsForm(ModelForm):
    start_date = forms.DateField(widget=TextInput(attrs={'class': 'form-control input-sm','readonly':''}))
    start_hour = forms.TimeField(widget=TimeInput(attrs={'class': 'form-control input-sm input-append date', 'id':'starthour','readonly':''}))
    end_hour = forms.TimeField(widget=TextInput(attrs={'class': 'form-control input-sm',
                                     'id':'endhour','readonly':''}))
    error_css_class = 'has_error'
    required_css_class = 'has_warning'

    def __init__(self, *args, **kwargs):

        self.fields['start_date'] = self.instance.start.date()
        self.fields['start_hour'] = self.instance.start.time()
        self.fields['end_hour'] = self.instance.end.time()


    class Meta:
        model = Entry
        exclude = ('start', 'end', 'creator')
        widgets = {            
            'reason':Textarea(attrs={'class':'form-control input-sm'}),
            'title': TextInput(attrs={'class': 'form-control input-sm'}),
            'comment':Textarea(attrs={'class': 'form-control input-sm'}),
            'patient': Select(attrs={'class':'form-control input-sm selectpicker',
                                      'data-live-search':'true'}),
            'event_category': Select(attrs={'class':'form-control input-sm'}),
            'doctor': Select(attrs={'class': 'form-control input-sm selectpicker',
                                     'data-live-search':'true'})

        }

    def save(self, commit=True):
        print 'Form save method'
        model = super(EntryDetailsForm, self).save(commit=False)
        model.start = datetime.combine(self.cleaned_data['start_date'], self.cleaned_data['start_hour'])
        model.end = datetime.combine(self.cleaned_data['start_date'], self.cleaned_data['end_hour'])

但是我得到一个错误,我的EntryDetailsForm对象没有实例属性。我做错了吗?

编辑使用此方法不会填充start_date start_hour和end_hour字段的值。我如何在__init__

中执行此操作

EDIT2:我在视图中使用了初始参数

entry_form = EntryDetailsForm(instance=entry, initial={'start_date':...etc})

并且工作了。有没有办法使用 init

1 个答案:

答案 0 :(得分:1)

在使用super(EntryDetailsForm, self).__init__(*args, **kwargs)之前,您需要致电self.instance