Django default=timezone.now + delta - django

Trying to set a timestamp for a key expiration in Django model and bumped into this issue :
My current code :
key_expires = models.DateTimeField(default=timezone.now() + timezone.timedelta(days=1))
The code above works, however when "timezone.now()" is used, it gets the timestamp form the time when Apache was restarted, so this doesn't work. I did some research and found the solution for that part of the issue, so by replacing "timezone.now()" with "timezone.now", I'm getting the current time stamp every time the object is created, which is perfect, issue is partially solved.
I'm having trouble changing the date by using the "timezone.timedelta(days=1)".
key_expires = models.DateTimeField(default=timezone.now + timezone.timedelta(days=1))
Error I'm getting is :
key_expires = models.DateTimeField(default=timezone.now + timezone.timedelta(days=1))
TypeError: unsupported operand type(s) for +: 'function' and 'datetime.timedelta'
The goal is to set the time stamp 24 hours ahead.
Any help is greatly appreciated.

default takes a callable, so you just need to write a function to do what you want and then provide that as the argument:
def one_day_hence():
return timezone.now() + timezone.timedelta(days=1)
class MyModel(models.Model):
...
key_expires = models.DateTimeField(default=one_day_hence)
(As discussed here, resist the temptation to make this a lambda.)

Related

Unable to add a date time value in Cassandra DB? Invalid syntax error?

Problem:
I'm currently trying to insert a date time object into my Cassandra database using the following code:
dt_str = '2016-09-01 12:00:00.00000'
dt_thing = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S.%f')
def insert_record(session):
session.execute(
"""
INSERT INTO record_table (last_modified)
VALUES(dt_thing)
"""
)
However, I'm receiving the following error:
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 3:17 no viable alternative at input ')' (...record_table (last_modified) VALUES([dt_thing])...)">
Background Info
I'm relatively new to Cassandra and I'm not sure how to go about this. What I'm basically trying to do is add an existing date time value in my database since an earlier version of the code is looking for one but it does not exist yet (hence, why I'm manually adding one).
I'm using Python 2.7 and Cassandra 3.0.
Any input or how to go about this would be great!
I answered a similar question yesterday. But the general idea, is that you'll want to define a prepared statement. Then bind your dt_thing variable to it, like this:
dt_str = '2016-09-01 12:00:00.00000'
dt_thing = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S.%f')
def insert_record(session):
preparedInsert = session.prepare(
"""
INSERT INTO record_table (last_modified)
VALUES (?)
"""
)
session.execute(preparedInsert,[dt_thing])
Also, I don't recommend using a timestamp as a lone PRIMARY KEY (which is the only model for which that INSERT would work).

Training Doc2Vec on 20newsgroups dataset. Getting Exception AttributeError: 'str' object has no attribute 'words'

There were a similar question here Gensim Doc2Vec Exception AttributeError: 'str' object has no attribute 'words', but it didn't get any helpful answers.
I'm trying to train Doc2Vec on 20newsgroups corpora.
Here's how I build the vocab:
from sklearn.datasets import fetch_20newsgroups
def get_data(subset):
newsgroups_data = fetch_20newsgroups(subset=subset, remove=('headers', 'footers', 'quotes'))
docs = []
for news_no, news in enumerate(newsgroups_data.data):
tokens = gensim.utils.to_unicode(news).split()
if len(tokens) == 0:
continue
sentiment = newsgroups_data.target[news_no]
tags = ['SENT_'+ str(news_no), str(sentiment)]
docs.append(TaggedDocument(tokens, tags))
return docs
train_docs = get_data('train')
test_docs = get_data('test')
alldocs = train_docs + test_docs
model = Doc2Vec(dm=dm, size=size, window=window, alpha = alpha, negative=negative, sample=sample, min_count = min_count, workers=cores, iter=passes)
model.build_vocab(alldocs)
Then I train the model and save the result:
model.train(train_docs, total_examples = len(train_docs), epochs = model.iter)
model.train_words = False
model.train_labels = True
model.train(test_docs, total_examples = len(test_docs), epochs = model.iter)
model.save(output)
The problem appears when I try to load the model:
screen
I tried:
using LabeledSentence instead of TaggedDocument
yielding TaggedDocument instead of appending them to the list
setting min_count to 1 so no word would be ignored (just in case)
Also the problem occurs on python2 as well as python3.
Please, help me solve this.
You've hidden the most important information – the exact code that triggers the error, and the error text itself – in the offsite (imgur) 'screen' link. (That would be the ideal text to cut & paste into the question, rather than other steps that seem to run OK, without triggering the error.)
Looking at that screenshot, there's the line:
model = Doc2Vec("20ng_infer")
...which triggers the error.
Note that none of the arguments as documented for the Doc2Vec() initialization method are a plain string, like the "20ng_infer" argument in the above line – so that's unlikely to do anything useful.
If trying to load a model that was previously saved with model.save(), you should use Doc2Vec.load() – which will take a string describing a local file path from which to load the model. So try:
model = Doc2Vec.load("20ng_infer")
(Note also that larger models might be saved to multiple files, all starting with the string you supplied to save(), and these files must be kept/moved together to again re-load() them in the future.)

calling a function to obtain a model field value

I'm trying to get a unique value for a field (unique within the db column).
my code (other model fields omitted):
class PlatformUserChildren(models.Model):
dashboard = models.CharField('dashboard URL', max_length=64, unique=True, default=createDashboardCode(self))
def createDashboardCode(self):
stringCheck = False
while stringCheck is False:
newString = str(uuid.uuid4())[:32]
doesStringExist = newString in self.dashboard
if not doesStringExist:
stringCheck = True
return newString
I'm getting name 'self' is not defined as an error.
What should I be passing to the function so that I can check the db column to ensure the value is unique -or- is there a built-in way of doing this?
What I've already tried or looked at:
setting unique=True for the field and using default=uuid.uuid4 - that gives me duplicate values and generates a validation error (SO link)
I'm aware of Django 1.8's UUID field, however i'm on 1.7
The problem lies in the following line (indented for better readability) as you already know and mentioned before:
dashboard = models.CharField(
'dashboard URL',
max_length=64,
unique=True,
default=createDashboardCode(self)
)
In this part:
default=createDashboardCode(self)
you're calling the method createDashboardCode with the argument self. This is wrong, because you never pass self to a method as it is passed by Python. Whenever you call the method createDashboardCode you should do it this way:
createDashboardCode()
That's it, you're not passing the argument self explicitly.
You're getting an error "name 'self' is not defined" because self is not defined. There is no variable self in your code that you can pass to the method.
Now we're one step further, but your problem won't be solved if you just apply this slight change to your code.
The return value from the method createDashboardCode will be assigned to default. That's not what you really want. You have to assign a reference of the method to default:
default = createDashboardCode
Pay attention to the missing brackets. This will call the method every time a new instance of the model is created
Define a function:
def my_function():
print "hello"
and run it in the Python interpreter:
# once like this
my_function()
# and again like this
my_function
and you'll see the difference. That should help you to better comprehend this issue.

Django assertEqual does not show actual vs expected values

So I'm learning how to practice TDD in Django and I'm having some minor trouble. I created a custom user object that links to authenticated system users in a one to one relationship. I have the following test, which exercises part of my custom user class:
def test_creating_a_user_with_attributes(self):
myuser = Myuser.objects.create_user('Gary', email='me#email.com')
current_time = now()
myuser.birthday = current_time
myuser.save()
first_user = Myuser.objects.all()[0]
self.assertEqual(first_user.birthday, current_time, 'first_user.birthday should be equal to the current_time')
The problem is that my test was failing and I couldn't immediately see why. The assert failure reported the message I had supplied and I was confused because I was certain that the birthday was set to the value of now. I ended up having to refactor my assert to make the failing value clear.
self.assertEqual(first_user.birthday, current_time,
'first_user.birthday ' + str(first_user.birthday) + ' should equal ' + str(current_time))
This revealed that the birthday was a date field and not a datetime field. My question is wether there exists some alternate form of assert that dumps the expected and actual values as part of the failure message or if I am somehow misusing or misunderstanding the API?
Django doesn't implement assertEqual, it simply uses Python's unittest module for that one.
What you need is to set the longMessage attribute to True for your test case class, like so:
class VerboseTestCase(TestCase):
longMessage = True
def test_creating_a_user_with_attributes(self):
myuser = Myuser.objects.create_user('Gary', email='me#email.com')
current_time = now()
myuser.birthday = current_time
myuser.save()
first_user = Myuser.objects.all()[0]
self.assertEqual(first_user.birthday, current_time, 'first_user.birthday should be equal to the current_time')
Which will output something like this if the test fails:
AssertionError: <datetime 1> != <datetime 2> : first_user.birthday should be equal to the current_time
This is explained in Python's unittest docs.
The default error message does show the values that failed. But you have overridden that by supplying a third argument to assertEqual. If you left that out, it would print the values.
As Gonzalo shows, you can in fact get the best of both worlds by using the longMessage attribute.

What does the Django "expected string or buffer" error indicate?

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!
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.
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.
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.
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.
'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}
)
str(yourvar)
Ou can convert sting your variables.