python - AttributeError:模块没有属性
问题描述
当我尝试将 auth_code(模型类中的变量)中使用的函数名称“random_string”更改为任何其他名称时,它会在命令行中显示错误:AttributeError: module 'users_data.models' has no attribute 'random_string'
from django.db import models
from django.utils.timezone import now
import random
from django.core.exceptions import ValidationError
def random_string():
return int(random.randint(000000, 999999))
def validate_phone_number(phone):
if len(phone) < 7:
raise ValidationError('Phone number can not be less than 7 digits')
class Users(models.Model):
phone = models.CharField(verbose_name='Phone', max_length=20, validators=
[validate_phone_number])
auth_code = models.IntegerField(verbose_name='Code',
default=random_string)
get_in_date = models.DateTimeField(default=now, blank=False,
editable=False)
我看过很多帖子涵盖了我的问题,但我没有发现任何有用的东西。我将不胜感激任何帮助。
解决方案
问题出在您的迁移文件中,如本期所示。基本上,当您生成以前的迁移文件时,会写入字段的默认值是random_string
.
现在,如果您更改该函数名称,您当前的代码将起作用,但由于您已经生成的迁移文件使用此函数,它们将引发错误,因为它们无法再找到该函数。
我不知道仅更新文件以替换其中的名称是否就足够了。其他解决方案是重置迁移(尽管这可能会产生成本)。
我提供的链接提供了一个脚本来解决这个问题,但我自己没有测试过
推荐阅读
- jquery - 如何在 JQuery FancyTree 中部分选择节点?
- android - APK 文件可在 android 模拟器中运行,但无法安装在我的设备上
- scala - 确保扇入元素属于同一个扇出元素
- regex - 匹配 oracle regexp_like 中的行首
- java - 在 Keycloak 扩展档案中放置消息的位置
- java - 优化在数字中添加零填充
- c++ - C++不支持非成员虚函数的原因是什么
- vba - View.GoToDate 没有去日期
- android - Android如何杀死一个Activity?
- c# - IWebBrowser2 从本机 ActiveX 控件获取未成功