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

在Django Rest Framework中遇'module'对象不可调用错误求助

解决TypeError: 'module' object is not callable的问题

嘿,我一眼就揪出问题所在了!你的报错根源其实在settings.py的DRF配置里,具体是认证类的配置出了错。

错误原因拆解

先看你settings.py里的这段配置:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authtoken',  # 这里就是问题核心!
    ],
    # ...其他配置
}

'rest_framework.authtoken'是一个Python模块,而DRF的DEFAULT_AUTHENTICATION_CLASSES要求的是可调用的认证类,不是模块本身。当DRF初始化认证器时,会遍历这个列表里的每一项,尝试执行auth()来实例化认证对象,但模块是不能被调用的,这就直接触发了TypeError: 'module' object is not callable。

修复步骤

1. 修正认证类配置

把错误的模块路径替换成正确的认证类路径:'rest_framework.authtoken.authentication.TokenAuthentication',修改后的配置如下:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authtoken.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

2. (可选但关键)修复序列化器拼写问题

另外注意到你serializers.py里的field是单数,这会导致DRF无法识别你要序列化的字段,后续大概率会出问题,建议改成复数fields:

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = CategoryModel
        fields = ['name', 'description']  # 把field改为fields

验证修复

保存所有修改后,重启Django服务器,再访问你的API接口,这个TypeError应该就彻底消失了。目前你的views和urls配置是没问题的,不用调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:29:59