B
B
blazer052016-06-23 12:49:58
Django
blazer05, 2016-06-23 12:49:58

Django - error while doing makemigrations?

Hello.
There is a problem with one field in the model.

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    activation_key = models.CharField(max_length=40, blank=True)
    key_expires = models.DateTimeField(default=datetime.date.today())

    def __unicode__(self):                
        return self.user.username

    class Meta:
        verbose_name_plural=u'User profiles'

I have django 1.8.6 and when doing migration there is a problem with this field key_expires = models.DateTimeField(default=datetime.date.today()), writes an error
AttributeError: 'method_descriptor' object has no attribute 'today' - has no type attribute 'today'.
If you specify something else here or remove everything altogether, then another error will fall out like this
TypeError: unbound method deconstruct() must be called with DateTimeField instance as first argument (got nothing instead)
I left the field like this key_expires = models.DateTimeField ()
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2016-06-23
@deliro

1) In default you stuff the RESULT of the function, not the function itself. That. the default value for all key_expires fields will be exactly when you last made makemigrations. By the way, you can do makemigrations endlessly, there will always be something new :)
2) You are trying to assign a date to the Date Time field. There is a DateField for this.
3) There are two huge differences between:

import datetime
datetime.date.today()

and
from datetime import datetime
datetime.date.today()

In the first case, you get the date class from the datetime module, which has a today method.
In the second case, you get the (supposedly) date class method from the datetime class and it (supposedly) should have a today method, which, of course, is not.
4) It's the middle of 2016, people have been redefining user models for a long time, not O2O crutches. Read at least here . The same applies to the second python.
The solution to your problem is:
key_expires = models.DateField(auto_now_add=True)

M
marazmiki, 2016-06-23
@marazmiki

You pass to default= not a callable function, but its computed value at the time the program starts. The problem is that key_expires will default to the server start date. On the next day of work, this will be yesterday's date :)
if you write like this:

key_expires = models.DateTimeField(default=datetime.date.today)
those. without brackets, the application will work correctly. And migrations will be created as a nice bonus.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question