What does the Django “expected string or buffer” error indicate?
-
29-09-2019 - |
Question
I've been stuck with this error for quite a while now and I just can't figure out what it means. It occurs when I try to save an object to my mysql database. Any ideas?
Thanks for the help!
Solution
This probably means that Python is trying to execute code which is expecting a certain datatype (bool, string, int, etc.), but an other, incorrect, datatype is provided.
OTHER TIPS
Just ran into the same problem and resolved it. I instantiated a form like this:
data = {'date' : datetime.now} #this is the problem
form = MyForm(data)
That form was saved later on and django tried to set 'date' in the model. But datetime.now refers to a function rather than a date, obviously. What I wanted to do was datetime.now()
Maybe this helps anybody running into this in future.
In my case it was appears when I use "time" library to convert date string to datetime object. I just use "datetime.strptime" instead of "time.strptime"and problem vanished.
'expiration' is this field
expiration = models.DateTimeField(default=7)
And code with error was this one:
ex = timedelta(minutes=expiration)
authobj, created = cls.objects.update_or_create(
operator=operator,
defaults={'transport':transport,'token':cls.generate_key(40),'expiration':ex}
)
And it was solved by setting it like this (instead of timedelta, a date)
ex = datetime.now() + timedelta(minutes=expiration)
authobj, created = cls.objects.update_or_create(
operator=operator,
defaults={'transport':transport,'token':cls.generate_key(40),'expiration':ex}
)
The datetime validator in django is in the file:
/path/to/project/venv/lib/python2.7/site-packages/django/utils/dateparse.py
or in the site-packages of your current python interpreter.
Have a look there to see the regular expressions. In my case, the way to solve it was:
ended=datetime.fromtimestamp(time.time())
other=datetime.fromtimestamp(time.time())
# in the model:
ended = models.DateTimeField(blank=True, null=True) # or
other = models.DateTimeField(auto_now_add=False, blank=True)
both working.
str(yourvar)
Ou can convert sting your variables.