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

升级Django 5.0后遇AttributeError:'BlankChoiceIterator'无__len__属性

Django 5.0升级后AttributeError: 'BlankChoiceIterator' object has no attribute 'len' 解决方案

错误根源

这个报错是django-countries第三方库与Django 5.0的兼容性问题。Django 5.0优化了表单选项迭代器的实现,引入了BlankChoiceIterator这类轻量迭代器,不再强制要求实现__len__方法;而旧版django-countries的widgets.py中,get_choices方法直接尝试将self._choices转换为列表,触发了不存在的__len__属性调用。

解决方案

方案1:升级django-countries到兼容版本

这是最直接的解决方式,执行以下命令升级到支持Django 5.0的版本(要求版本≥7.0):

pip install --upgrade django-countries

方案2:临时修改库源码(无法升级时使用)

如果暂时无法升级库,可以手动修改django-countries的widget代码:

  1. 找到你的虚拟环境中django-countries的widget文件,路径类似:dirto/env/lib/python3.10/site-packages/django_countries/widgets.py
  2. 找到get_choices方法,替换原有代码:
    原代码:
    def get_choices(self):
        self._choices: ChoiceList = list(self._choices)
        return super().get_choices()
    
    修改为:
    def get_choices(self):
        # 先将迭代器转为列表,避免直接调用无__len__的对象
        self._choices = list(iter(self._choices))
        return super().get_choices()
    
  3. 保存文件后重启Django服务即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 02:13:27