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

使用django_countries模块遇AttributeError错误,疑与Django新版本有关

问题分析与解决

这个错误确实和Django新版本(主要是3.2及之后版本)有关。Django 3.2重构了ChoiceIterator相关的迭代器实现,而你使用的CountryField(大概率是第三方包如django-countries提供的字段)未适配这个变更,导致Admin页面渲染下拉选项时,调用BlankChoiceIterator的__len__方法失败。

解决方法:

  • 若使用的是django-countries包,直接升级到2.2.0及以上版本,新版本已修复和Django 3.2+的兼容性问题。
  • 暂时无法升级包的话,可在Admin中自定义表单控件避开这个问题,示例代码如下:
from django import forms
from django.contrib import admin
from .models import Person1
from django_countries.fields import CountryField

class Person1AdminForm(forms.ModelForm):
    country = CountryField().formfield(widget=forms.Select)
    
    class Meta:
        model = Person1
        fields = '__all__'

class Person1Admin(admin.ModelAdmin):
    form = Person1AdminForm

admin.site.register(Person1, Person1Admin)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:32:33