NDOJ/judge/widgets/datetime.py

50 lines
1.7 KiB
Python
Raw Normal View History

from django import forms
2024-04-13 03:26:17 +00:00
from django.templatetags.static import static
from django.utils.html import format_html
from django.forms.utils import flatatt
2024-04-13 05:51:14 +00:00
from django.utils.dateparse import parse_datetime
class DateTimePickerWidget(forms.DateTimeInput):
2024-04-13 03:26:17 +00:00
input_type = "datetime-local"
2024-04-13 03:26:17 +00:00
def render(self, name, value, attrs=None, renderer=None):
if value is None:
value = ""
2024-04-13 05:51:14 +00:00
elif isinstance(value, str):
# Attempt to parse the string back to datetime
parsed_date = parse_datetime(value)
if parsed_date is not None:
value = parsed_date.strftime("%Y-%m-%dT%H:%M")
else:
value = ""
2024-04-13 03:26:17 +00:00
else:
value = value.strftime("%Y-%m-%dT%H:%M")
2024-04-13 03:26:17 +00:00
final_attrs = self.build_attrs(
attrs, {"type": self.input_type, "name": name, "value": value}
)
2024-04-13 03:26:17 +00:00
return format_html("<input{}>", flatatt(final_attrs))
2024-04-27 03:51:16 +00:00
class DatePickerWidget(forms.DateInput):
input_type = "date"
def render(self, name, value, attrs=None, renderer=None):
if value is None:
value = ""
elif isinstance(value, str):
# Attempt to parse the string back to date
parsed_date = parse_date(value)
if parsed_date is not None:
value = parsed_date.strftime("%Y-%m-%d")
else:
value = ""
else:
value = value.strftime("%Y-%m-%d")
final_attrs = self.build_attrs(
attrs, {"type": self.input_type, "name": name, "value": value}
)
return format_html("<input{}>", flatatt(final_attrs))