Django 提示:AttributeError : ‘module‘ object has no attribute ‘utcnow‘
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 提示:AttributeError : ‘module‘ object has no attribute ‘utcnow‘相关的知识,希望对你有一定的参考价值。
问题描述:今天使用Django+pyjwt 实现前后端分离基于token 凭证方式,我在实体对象(User)定义生成token 相关方法,核心代码如下:
models.py
from django.conf import settings
from django.db import models
import jwt
import datetime
# Create your models here.
class Book(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=255, null=True)
cover = models.CharField(max_length=255)
author = models.CharField(max_length=255)
price = models.DecimalField(decimal_places=2, max_digits=100000)
is_delete = models.IntegerField()
class Meta:
managed = False
db_table = 'book'
class User(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=255, null=True)
passwd = models.CharField(max_length=255, null=True)
@property
def token(self):
return self._generate_jwt_token()
def _generate_jwt_token(self):
token = jwt.encode({
'exp': datetime.utcnow() + datetime.timedelta(days=1),
'iat': datetime.utcnow(),
'data': {
'name': self.name
}
}, settings.SECRET_KEY, algorithm='HS256')
return token.decode('utf-8')
class Meta:
managed = False
db_table = 'user'
上述代码会提示相关错误信息:'module' object has no attribute 'utcnow'
解决办法:
方式一:
import datetime
datetime.datetime.utcnow()
方式二: 我选用的方式
from datetime import datetime
datetime.utcnow()
修改后的代码片段截图
以上是关于Django 提示:AttributeError : ‘module‘ object has no attribute ‘utcnow‘的主要内容,如果未能解决你的问题,请参考以下文章
django错误笔记(xadmin)——AttributeError: 'Settings' object has no attribute 'TEMPLATE_CONTEXT
Django 1.8 AttributeError:模块没有属性'urls'
django - AttributeError:'AnonymousUser'对象没有属性'todo'
Django 3:AttributeError:'AdminSite'对象没有属性'Register' [关闭]