How to use DateField in an ArrayField in django

46 Views Asked by At

I'm trying to use ArrayField in my model. I get it working with, e.g., IntegerField, but not DateField. So I'm wondering, is there some limitation I'm not aware of, or is there a bit missing in my code that prevents it from working?

In my models.py, I added the field with

class Directive(models.Model):

    id = models.AutoField(primary_key=True)
    ...
    individual_dates = ArrayField(
        models.DateField(auto_now_add=False, blank=True, default=date.today),
        default=list,)
    test = ArrayField(models.IntegerField(blank=True), default=list,)
    ...

and in my forms.py, I have

class DirectiveForm(forms.ModelForm):

    individual_dates = SimpleArrayField(
        forms.DateField(), required=False,
        help_text='comma separated list of dates',
        widget=DatePickerInput(options={'format': 'DD.MM.YYYY'}))
    test = SimpleArrayField(
        forms.IntegerField(), required=False,
        help_text='comma separated list of ints')

    ...

The form renders fine: fields as rendered with template

Now,

  • when I enter a comma seperated list of integers in the "test" field, the values are stored in the database as expected.
  • when I try to enter a number of dates in the "individual dates" field using the DatePicker, every pick overwrites the previous one, and the last one is eventually stored in the database.
  • when I enter a comma separated list of dates by hand, only the first entry is stored in database.

But,

  • when I use the django shell, import my model and try to enter dates there, it works as expected:
>>> Directive.objects.create(individual_dates=[date(2024,2,2), date(2024,3,1), date(2024,4,6)])
>>> Directive.save()
>>> Directive.objects.last().individual_dates
[datetime.date(2024, 2, 2), datetime.date(2024, 3, 1), datetime.date(2024, 4, 6)]

So, what am I doing wrong in my forms.py (or in my template?) which prevents the ArrayField to store all values? Do I need to customize the clean() method to correctly account for dates? But that wouldn't solve the issue with the DatePicker...

0

There are 0 best solutions below