Categories
Python Answers

How to use Python Django time/date widgets in custom form?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *