django报错

1.通过代码直接进行数据库操作,而不是通过shell时报错django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

一种方法,在import模型之前添加以下代码。指定使用配置文件。可以直接复制manage.py下的

import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'untitled.settings')
django.setup()

 第二种是直接编辑配置,勾选run with python console

2.使用DecimalField提示Ensure that there are no more than 2 decimal places

    money = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2)

这是个十进制的小数,相当于Python的Decimal实例。decimal_places=2表示2位小数,但是我直接用两位小数的浮点数时,比如1230.33保存缺报错了。原因在于直接使用浮点数转为十进制时后面小数位其实很长

from decimal import *

money = 1230.33
print(Decimal(money))
money1 = str(money)
print(Decimal(money1))

估计保存的时候有调用Decimal()这个方法,直接传浮点数是不行的。可以传字符串,或者Decimal()方法处理后的值。

3.通过Django插件来自动将Django model的help_text当做注释迁移到数据库中

pip install django-comment-migrate
INSTALLED_APPS =[
"django_comment_migrate",
 ...
]

4.模型中的error_messages自定义错误不起作用

这是因为模型对象在调用save()方法时是不会校验这些的。需要先调用full_clean()方法来进行校验

5.在模型字段IntegerField中使用max_length参数来进行长度校验,启动server服务时报错。

使用内置的validators来进行校验

from django.core.validators import MinValueValidator,MaxValueValidator

validators=[MaxValueValidator(1), MinValueValidator(1)]

6.RuntimeWarning: DateTimeField CaseModel.created_time received a naive datetime (2022-07-28 17:56:11) while time zone support is active.
  warnings.warn(

    created_time = models.DateTimeField(default=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

自带的参数保存的时间 时分秒显示有问题,所以想用默认值来处理,然后就提示这个

修改setting文件的USE_TZ = False即可

7.UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list

列表查询缺少排序,增加order_by,或者ordering

8.auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'interface.User.groups'.

因为继承AbstractUser,拓展user表字段,需要在setting文件中添加AUTH_USER_MODEL

AUTH_USER_MODEL = 'interface.User'

api名称.拓展的类名

9.去掉DateTimeField的毫秒数

from django.db.backends.mysql.base import DatabaseWrapper

Ctrl+鼠标左键点击DatabaseWrapper跳转到相应源码,去掉(6)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值