0

I am trying to setup a Model and a corresponding ModelForm with django containing a DateField/Input.

from django.db import models

class MyModel(models.Model):
    myDate = models.DateField()

from django import forms

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = "__all__"
        widgets = {
            'myDate': forms.DateInput(format=("%d/%m/%Y")) 
        }

But sadly, when I enter a date in the form that results out of MyModelForm, the day and the month get exchanged. E.g. 1/2/22 will result in January 2nd 2022 instead of feburary 1st 2022. What else do I need to do, so the date gets interpreted properly?

Blackbriar
  • 477
  • 4
  • 14

1 Answers1

1

Specifying the format only in your widget’s form is just used as a display, you still need to pass it to specify the field myDate as a DateField in your form:

from django.db import models

class MyModel(models.Model):
    myDate = models.DateField()

from django import forms

class MyModelForm(forms.ModelForm):
    myDate = forms.DateField(input_formats=["%d/%m/%Y"])

    class Meta:
        model = MyModel
        fields = "__all__"
        widgets = {
            'myDate': forms.DateInput(format=("%d/%m/%Y")) 
        }

Another option to set this up would be to add the format inside the DATE_INPUT_FORMAT variable in settings.py. See https://docs.djangoproject.com/en/4.0/ref/settings/#date-input-formats for more

mtzd
  • 759
  • 4
  • 16
  • 1
    Adding your suggestion inside MyModel results in an error: `TypeError: Field.__init__() got an unexpected keyword argument 'input_formats'` – Blackbriar May 07 '22 at 12:51
  • Sorry about that, I thought I was reading from the `model.DateField` docs but it was from `form.DateField`. Edited the answer to account for that – mtzd May 07 '22 at 13:03
  • Also this question might be useful too https://stackoverflow.com/questions/30911612/how-can-i-set-a-datefield-format-in-django-from-the-model – mtzd May 07 '22 at 13:03