You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm thinking that we have to create Custom Form field PartialDateField that receive ISO Format date that create cleaned_data in form of PartialDateField Object
I wrote a custom form widget with a nicer UI for PartialDate fields based on Django's SelectDateWidget.
The code looks like this:
class PartialDateWidget(forms.SelectDateWidget):
def get_context(self, name, value, attrs):
# reorder the subwidgets to year, month, day
context = super().get_context(name, value, attrs)
m, d, y = context["widget"]["subwidgets"]
context["widget"]["subwidgets"] = [y, m, d]
return context
def format_value(self, value):
# convert PartialDate to dict for SelectDateWidget
if isinstance(value, PartialDate):
return {
"year": value.date.year,
"month": value.date.month if value.precision >= PartialDate.MONTH else None,
"day": value.date.day if value.precision == PartialDate.DAY else None,
}
return {"year": None, "month": None, "day": None}
def value_from_datadict(self, data, files, name):
# build a PartialDate from the separate fields
y = data.get(self.year_field % name)
m = data.get(self.month_field % name)
d = data.get(self.day_field % name)
if y == m == d == "":
return None
# build the date string
value = y
if m:
value += f"-{m}"
if m and d:
value += f"-{d}"
return value
and the end result in the admin site is this:
I use the widget in my admin classes by specifying it in formfield_overrides, however, it would be fairly trivial to create a custom form field that can be used in any form.
If you like, I'd be happy to write some tests and submit a pull request.
Activity
lorinkoz commentedon Aug 13, 2020
How do you envision it?
RafifEL commentedon Aug 13, 2020
I'm thinking that we have to create Custom Form field PartialDateField that receive ISO Format date that create cleaned_data in form of PartialDateField Object
SamuelJennings commentedon May 13, 2024
I wrote a custom form widget with a nicer UI for
PartialDatefields based on Django's SelectDateWidget.The code looks like this:
and the end result in the admin site is this:
I use the widget in my admin classes by specifying it in formfield_overrides, however, it would be fairly trivial to create a custom form field that can be used in any form.
If you like, I'd be happy to write some tests and submit a pull request.