Django - need datetime fields that can only process a year, as well as year and month values

I need to be able to write only the year, year or month (in addition to the standard full date and time values) in some of my datetime fields. Like these pictures below.

YYYY
YYYY-MM
YYYY-MM-DD
YYYY-MM-DD HH
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS

In mySQL, this can easily be done using zeros, but this does not work in django. This is a dumb python time.datetime function that does not support it.

Is there an easy way to do this in django? If not, are there any extensions that can do this for me? If not, how can I solve this in the best way?

It would be good for me if he could cope with the normalization of local time material, if that was the full value of the data time. That way, I could use the same field everywhere. But this is not very important.

+5
source share
2 answers

Perhaps this would help:

DayMonthField and YearField

django-yearlessdate - https://github.com/seddonym/django-yearlessdate

YearMonthField

YEARMONTH_INPUT_FORMATS = (
    '%Y-%m', '%m/%Y', '%m/%y', # '2006-10', '10/2006', '10/06'
)

class YearMonthField(CharField):
    default_error_messages = {
        'invalid': _('Enter a valid year and month.'),
    }

    def __init__(self, input_formats=None, *args, **kwargs):
        super(YearMonthField, self).__init__(*args, **kwargs)
        self.input_formats = input_formats

    def clean(self, value):
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return format(value, '%Y-%m')
        if isinstance(value, datetime.date):
            return format(value, '%Y-%m')
        for fmt in self.input_formats or YEARMONTH_INPUT_FORMATS:
            try:
                date = datetime.date(*time.strptime(value, fmt)[:3])
                return format(date, '%Y-%m')
            except ValueError:
                continue
        raise ValidationError(self.error_messages['invalid'])

class MyModel(models.Model):
    yearmonth = YearMonthField() 
+7
source

There is also django-monthfield, which uses a date field in the database, but a widget that selects only the year and month:

https://github.com/clearspark/django-monthfield

0
source

All Articles