1

I am using docker-compose for a registration form, where the api and database reside in separate containers. The response on registration shows system date and time, which I wanted, but in postgres date field shows incorrect data, and I don't know which time format it is using. The code was written in python with Django framework.Please help me in this. Following is the postman response:

{
    "success": 1,
    "msg": "Registration Success",
    "details": {
      "email": "test22@gmail.com",
      "mobile_num": "5698745210",
      "date_joined": "2020-06-27T14:43:28.329284",
      "user_type": [
         "Companion",
         "Community"
       ],
      "otp_verified": false
     }
}

Here the date_joined field picks system datetime, which is not my concern, but in postgres database, data is like this:

 2020-06-27 09:13:28.329284+00
 

The time of registration was 2:30 pm, but postgres shows 9:13. The source code of model is here:

now = datetime.datetime.now()
class User(AbstractBaseUser, PermissionsMixin):
  email = models.EmailField(max_length=40, unique=True)
  date_joined = models.DateTimeField(default=now)
  user_type = ArrayField(models.CharField(max_length = 20))
  mobile_num = models.CharField(max_length = 15)
  otp_verified = models.BooleanField(default=False)

Also whenever I re-build a container, docker shows the log as:

django_app_1     | /usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1421: RuntimeWarning: DateTimeField User.date_joined received a naive datetime (2020-06-27 14:43:28.329284) while time zone support is active.
django_app_1     |   RuntimeWarning)

Can anyone tell me where I went wrong?

1 Answers1

0

Well you evaluate now() when the server starts, so it will each time add the time when the server started as default value. You can pass a callable instead, for example with:

from django.utils.timezone import now

class User(PermissionsMixin, AbstractBaseUser):
    email = models.EmailField(max_length=40, unique=True)
    date_joined = models.DateTimeField(default=now)
    user_type = ArrayField(models.CharField(max_length=20))
    mobile_num = models.CharField(max_length=15)
    otp_verified = models.BooleanField(default=False)

Here we thus do not pass a datetime object, but a function that will generate a datetime object.

It is however better to make use of the auto_now_add=True parameter [Django-doc] instead:

class User(PermissionsMixin, AbstractBaseUser):
    email = models.EmailField(max_length=40, unique=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    user_type = ArrayField(models.CharField(max_length=20))
    mobile_num = models.CharField(max_length=15)
    otp_verified = models.BooleanField(default=False)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555