-
-
Save saileshkush95/b30e1494053ce2aa33c002d8bb8011f6 to your computer and use it in GitHub Desktop.
django split datetime fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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