Skip to content

Add PartialDateForm #6

Open
Open

Description

@RafifEL

I think we need a PartialDateField in forms because of PartialDateField for models exist.

Activity

  1. lorinkoz commented on Aug 13, 2020

    @lorinkoz
    Collaborator

    How do you envision it?

  2. RafifEL commented on Aug 13, 2020

    @RafifEL
    Author

    How do you envision it?

    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

  3. SamuelJennings commented on May 13, 2024

    @SamuelJennings

    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:

    image

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions