Reputation: 1918
I have a Bootstrap datepicker and on date selection, I make an ajax call and send in the user selected date, I want to change the date of the object in the database, but I get this error from Django:
[u"'04/23/2018' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
How do I convert it to the specified format? This is my code:
Template:
$('#project_date').on('changeDate',function()
{
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
data: {
new_date: $('#project_date_input').val()
},
success: function(data){
//do something
}
views.py
def project_change_date(request, pk):
data = dict()
project = get_object_or_404(Project, pk=pk)
project.end_date = request.GET.get('new_date')
opp.save()
Upvotes: 2
Views: 2224
Reputation: 27503
import datetime
project.end_date = datetime.datetime.strptime(request.GET.get('new_date'), '%m/%d/%Y').strftime('%Y-%m-%d')
Upvotes: 1
Reputation: 9921
You can use a third party library like dateutil
In [14]: from dateutil.parser import parse
In [15]: c = "04/23/2018"
In [16]: parse(c)
Out[16]: datetime.datetime(2018, 4, 23, 0, 0)
In [17]: print(parse(c))
2018-04-23 00:00:00 # this format is same as your db's datetime format
Upvotes: 3