0

I have a postgresql9.6 table which has a char field: 'start_date', and the format like '20200101'.
And I created a Django2.0 model:

class TestModel(models.Model):
    start_date = models.DateField('start_date')

My admin.py is:

class TestAdmin(admin.ModelAdmin):
    list_display = ('start_date',)

admin.site.register(TestModel, TestAdmin)

And I also modify settings.py:

USE_L10N = False

DATE_INPUT_FORMATS = ['%Y%m%d']
DATE_FORMATS = ['%Y%m%d']

So I get the date in web form:'20200101', but when I save the form, shows a error:
'value has an invalid date format. It must be " "in YYYY-MM-DD format.'
I know the DateField save the date default use 'YYYY-MM-DD' format, but I need to change it to 'YYYYMMDD' so I can save the consistent data into pg database.
So how to overwriting the DateField or Model function to change the default format?

J.LOGAN
  • 29
  • 5

2 Answers2

1

You can use a CharField and use a DateInput widget in the model form for the model

class TestModel(models.Model):
    start_date = models.CharField(max_length=8)

class TestModelForm(forms.ModelForm):
    class Meta:
        model = TestModel
        fields = ['start_date']
        widgets = {'start_date': forms.DateInput(format='%Y%m%d')}

class TestAdmin(admin.ModelAdmin):
    form = TestModelForm
    list_display = ('start_date',)
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • Thanks, but I don't want to use text input type, I want to use datepicker widget, so can DateInput change it's input_type to work with datepicker? – J.LOGAN Apr 04 '20 at 08:10
0

Thanks to @Iain Shelvington, I finally got the solution to work my issue. Here is my code:

class TestModel(models.Model):
    start_date = models.CharField(max_length=8)

class TestModelForm(forms.ModelForm):
    class Meta:
        model = TestModel
        fields = ['start_date']
        widgets = {'start_date': forms.DateInput(format='%Y%m%d', attrs={'class': 'form-control', 'type': 'date'})}

class TestAdmin(admin.ModelAdmin):
    form = TestModelForm
    list_display = ('start_date',)

Typically, I modified the admin.py's save_model to save the date with YYYYMMDD to pg9.6:

 def save_model(self, request, obj, form, change):

        import re
        obj.start_date = str(re.sub('-', '', obj.start_date))
        obj.stop_date = str(re.sub('-', '', obj.stop_date))
        super().save_model(request, obj, form, change)
J.LOGAN
  • 29
  • 5