To use Python Django time/date widgets in custom form, we can use AdminTimeWidget
and AdminDateWidget
and AdminSplitDateTime
.
For instance, we write
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets
class ProductForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
to add the mydate
, mytime
, and mydatetime
fields and set them to AdminDateWidget
, AdminTimeWidget
, and AdminSplitDateTime
to use them as date or time widgets in our form.