1. 运行时前端显示:
A server error occurred. Please contact the administrator.
pycharm显示:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal mul
解决方法:
找到D:\python\Lib\site-packages\django\views\debug.py
# 将第334行替换
# with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open(encoding="utf-8") as fh:
2. 运行时报错提示html文件来源不存在
解决方法: 在settings.py中配置下 TEMPLATES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")], # 配置这一行
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
2. mysql数据类型对应的django类型
mysql的 bigint类型 => BigIntegerField类型
在Django中,可以使用BigIntegerField来对应数据库中的bigint类型。
BigIntegerField是一个64位整数字段,可以存储更大的整数值。
在自定义Django模型时,可以使用BigIntegerField来定义bigint类型的字段。
同时,如果需要在DRF中使用自定义的BigIntegerField,
需要自定义一个对应的反序列化器,将其转换为字符串类型,
以避免DRF默认将其转换为int类型。具体实现可以参考以下代码:
from django.db import models
class myModel(models.Model):
id = models.BigIntegerField(primary_key=True, db_column='id')
from rest_framework import serializers
# 定义一个类
class MySerField(serializers.IntegerField):
def to_representation(self, value):
return str(value)
# 序列化
class MyModelSerializer(serializers.ModelSerializer):
id = MySerField()
class Meta:
model = MyModel
fields = '__all__'
以上代码中,我们定义了一个MyModel模型,其中包含一个 id字段,
它对应数据库中的bigint类型。同时,我们自定义了一个MySerField反序列化器,
将bigint类型转换为字符串类型。最后,我们定义了一个MyModelSerializer序列化器,
将 id 字段使用自定义的MySerField反序列化器进行序列化。
这样,在使用DRF进行序列化和反序列化时,就可以正确地处理bigint类型的数据了。
3. django 解决时间格式带T的问题
只需要在settings.py中添加如下配置
REST_FRAMEWORK = {
'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}