You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

安装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不兼容。

解决方案

方案一:改用维护活跃的替代包(推荐)

  1. 卸载旧包
pip uninstall django-moneyfield
  1. 安装兼容新版本Django的django-money包
pip install django-money
  1. 修改模型代码适配新包的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
    )
  1. 重新执行迁移
python manage.py makemigrations
python manage.py migrate

方案二:降级Django到兼容版本(不推荐)

如果坚持使用django-moneyfield,只能将Django降级到1.8及以下版本,但该版本存在安全漏洞,不建议在生产环境使用。

内容的提问来源于stack exchange,提问作者Shaheem PP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:25:40