Skip to content

Instantly share code, notes, and snippets.

@saileshkush95
Forked from toshism/gist:1571984
Last active May 8, 2020 09:49
Show Gist options
  • Save saileshkush95/b30e1494053ce2aa33c002d8bb8011f6 to your computer and use it in GitHub Desktop.
Save saileshkush95/b30e1494053ce2aa33c002d8bb8011f6 to your computer and use it in GitHub Desktop.
django split datetime fields
#models.py
class Activity(models.Model):
name = models.CharField()
start = models.DateTimeField()
end = models.DateTimeField()
#forms.py
class ActivityForm(forms.ModelForm):
activity_date = forms.DateField()
start_time = forms.TimeField()
end_time = forms.TimeField()
class Meta:
model = Activity
fields = ('name', 'activity_date', 'start_time', 'end_time',)
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if kwargs['instance']:
self.fields['activity_date'].initial = kwargs['instance'].start.date()
self.fields['start_time'].initial = kwargs['instance'].start.time()
self.fields['end_time'].initial = kwargs['instance'].end.time()
def save(self, commit=True):
model = super(ActivityForm, self).save(commit=False)
model.start = datetime.combine(self.cleaned_data['activity_date'], self.cleaned_data['start_time'])
model.end = datetime.combine(self.cleaned_data['activity_date'], self.cleaned_data['end_time'])
if commit:
model.save()
return model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment