J.LOGAN
J.LOGAN

Reputation: 29

Django datefield default save format overwriting

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?

Upvotes: 0

Views: 504

Answers (2)

J.LOGAN
J.LOGAN

Reputation: 29

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)

Upvotes: 0

Iain Shelvington
Iain Shelvington

Reputation: 32294

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',)

Upvotes: 1

Related Questions