Home > Software engineering >  How to create Date from year and month (IntergerFields in Django Form)
How to create Date from year and month (IntergerFields in Django Form)

Time:08-11

I have a selection in Django Form based on year and month (as integer fields) and I would like to create and save also Date value (first day of particular month and year) to link it to another table.

My function in forms.py:

def date_creation(year, month):
        if year and month:
            y = str(year)
            m = str(month)
            if len(m) == 1:
                m = "0"  m
            entry = f"{y}-{m}-01 00:00:01"
            date1 = datetime.strptime(entry, '%Y-%m-%d %H:%M:%S')
            date2 = date1.strftime('%Y-%m-%d')
            return date2
        else:
            return 0

models.py

class MonthlyCosts(models.Model):

    y = int(date.today().year)
    y1 = y - 1
    y2 = y - 2
    year_selection = (
        (y, y),
        (y1, y1),
        (y2, y2),
    )

    months_selection = (
        (1, 'January'),
        (2, 'February'),
        (3, 'March'),
        (4, 'April'), 
        (5, 'May'),
        (6, 'June'),
        (7, 'July'),
        (8, 'August'),
        (9, 'September'),
        (10, 'October'),
        (11, 'November'),
        (12, 'December')
    )

    year = models.IntegerField("Year", choices=year_selection)
    month = models.IntegerField("Month", choices=months_selection)
    date = models.DateField("Date", null=True, blank=True)

When I tried function above in my form, so I got following error:

File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 349, in _strptime

raise ValueError("time data %r does not match format %r" %

ValueError: time data '<django.forms.fields.IntegerField object at 0x102c521c0>-<django.forms.fields.IntegerField object at 0x102c52280>-01 00:00:01' does not match format '%Y-%m-%d %H:%M:%S

Thanks a lot for help, L.

CodePudding user response:

It's because you passing formfieds to your date_creation function. you should do it in save method of form(asuming it's ModelForm):

def save(self, commit=True):
    year = self.cleaned_data['year']
    month = self.cleaned_data['month']
    self.instance.date = date_creation(year, month)
    return super(MonthlyCostsForm, self).save(commit)
  • Related