安装django-moneyfield后迁移报错:找不到django.forms.util模块
Django-moneyfield迁移报错:ModuleNotFoundError: 找不到'django.forms.util'模块
问题场景
使用pip install django-moneyfield安装金额字段后,在模型中定义了如下字段:
class Student(models.Model): user = models.ForeignKey(CustomUser, on_delete = models.CASCADE) fee = MoneyField(decimal_places = 2, max_digits = 8, amount_default = Decimal("0"), currency_default = "INR", null = True, blank = True)
执行迁移时触发错误:ModuleNotFoundError: No module named 'django.forms.util'
原因分析
django.forms.util模块在Django 1.9版本后被移除,而django-moneyfield这个包已多年未维护,代码中仍依赖该废弃模块,导致与当前使用的高版本Django不兼容。
解决方案
方案一:改用维护活跃的替代包(推荐)
- 卸载旧包
pip uninstall django-moneyfield
- 安装兼容新版本Django的
django-money包
pip install django-money
- 修改模型代码适配新包的API
from django.db import models from djmoney.models.fields import MoneyField class Student(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) fee = MoneyField( max_digits=8, decimal_places=2, default_currency='INR', null=True, blank=True, default=0 # 直接设置默认金额,无需单独指定amount_default )
- 重新执行迁移
python manage.py makemigrations python manage.py migrate
方案二:降级Django到兼容版本(不推荐)
如果坚持使用django-moneyfield,只能将Django降级到1.8及以下版本,但该版本存在安全漏洞,不建议在生产环境使用。
内容的提问来源于stack exchange,提问作者Shaheem PP
相关产品推荐
相关产品推荐

