Q:

Using instance variable inside a django form

I initialize a form using an instance of a model in my view like this
entry_form = EntryDetailsForm(instance=entry)

my model form is the following
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'])

But I get an error that my EntryDetailsForm object doesn't have an instance attribute. Am I doing something wrong?
EDIT Using this method won't populate the value of start_date start_hour and end_hour fields. How do I do that in __init__?
EDIT2: I used the initial parameter in my view
entry_form = EntryDetailsForm(instance=entry, initial={'start_date':...etc})

and worked. Is there a way to do using the init?

A:

You need to call super(EntryDetailsForm, self).__init__(*args, **kwargs), before self.instance usage.

