[Fixed]-Dealing with date formats from JSON to save in Django DateField


Just use django DATE_INPUT_FORMATS (https://docs.djangoproject.com/en/1.8/ref/settings/#date-input-formats) settings to specify allowed date format

DATE_INPUT_FORMATS = ("%d %b %Y",)

But take in consideration that this settings will work if you have disabled localization

USE_L10N = False

Otherwise django will use locale-dictated format.

In case if you need localization enabled, you should create your own locale date format.


The solution that I’ve provided works for data that is validated via Django Forms before interacting with models, not Django models directly.

You can otherwise use simple datetime.strptime() to change your date string to date object and then pass it to your model:

product_date = datetime.strptime(product_detail['productEndDate'], '%d %b %Y')

Or you can should first pass data that you receive after making a post request to appropriate form for validation and type conversion (because I didn’t see any validation in your code, maybe you just didn’t include it here) and only then pass data from the form to model.


Leave a comment