Craig
Craig

Reputation: 402

Issue Accessing DateTime Value (Unicode object has no attribute 'strftime')

I have an AJAX processed view that takes several pieces of information, two of which are unicode datetime values.

However, when I try to access the datetime values (start/end) directly from the object, it seems that it is still unicode.

I thought saving converted to datetime?

lid = int(postdata['lid'])
location = Group.objects.get(id=lid)
pgid = int(postdata['pgid'])
program = Group.objects.get(id=pgid)
start = postdata['start']
end = postdata['end']
eid = int(postdata['eid'])
creator = Employee.objects.get(id=eid)
description = postdata['description']

shift = ReliefShift()
shift.start = start
shift.end = end
shift.creator = creator
shift.description = description
shift.location = location
shift.program = program
shift.save()

alertModule = 'Relief Shifts Available'
alertMessage = 'A new relief shift has been posted for {0} from {1} to {2}. Visit the <a href="/staff/program/open-relief-shifts/">Relief Shifts page</a> for more details and to sign up.'.format(shift.location, shift.start.strftime('%b %d @ %I:%M%p'), shift.end.strftime('%b %d @ %I:%M%p'))

Upvotes: 1

Views: 2323

Answers (1)

Alasdair
Alasdair

Reputation: 308889

Calling shift.save() will save a datetime to the database, but it won't update shift. You could reload the shift object from the database after saving it, by calling refresh_from_db

shift.start = <unicode string>
shift.save()
# At this point, shift.start will still be a string
shift.refresh_from_db()

# refresh_from_db is new in Django 1.8. In early versions you would do:
shift = Shift.objects.get(pk=shift.pk)

It's not good practice to read values directly from the post data. It would be better to use a form or model form. Django will take care of converting the values into datetime objects, and you will be able to access the datetimes from form.cleaned_data, or from the instance if you are using model forms.

Upvotes: 1

Related Questions