I am using Python 3.6 and Django as web framework I have to save datetime together in my database but show date and time separate field in HTML. Model Code:
class date_time(models.Model):
date = models.DateField(default=timezone.now)
time = models.TimeField(default=timezone.now)
Form Code:
class date_time_Form(forms.ModelForm):
class Meta:
model = date_time
fields = ('date', 'time',)
widgets = {
'date': forms.TextInput(attrs={'class': 'form-control', 'type': 'date'}),
'time': forms.TextInput(attrs={'class': 'form-control', 'type': 'time'}),
}
labels = {
'date': 'Date',
'time': 'Time',
}
Currently, I am storing in a separate field but I want to save in one field date+time.
Update - I can use Datetime field but that will create only one element in HTML page.
But in HTML I want separate fields like below with only one datetime field in model
Is there any way to achieve this?
You can use SplitDateTimeField
: https://docs.djangoproject.com/en/3.0/ref/forms/fields/#splitdatetimefield
class Myform(forms.Form):
start_date = forms.SplitDateTimeField(initial=datetime.datetime.now)
Altough, if you want a label for each one, you will need to modify your template, or use separate form attributes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With