Django项目模块导入错误:No module named 'chat_app_backend.authentication'
解决Django跨应用导入模型/序列化器的ModuleNotFoundError问题
问题现象
开发Django项目时,chat应用的models.py和serializers.py中尝试导入authentication应用的内容时,均触发以下错误:
ModuleNotFoundError: No module named 'chat_app_backend.authentication'
相关代码与配置
chat应用models.py代码
from django.db import models from chat_app_backend.authentication.models import User class ChatRoom(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) picture = models.ImageField(upload_to='chatroom_pictures/', null=True, blank=True) number_of_users = models.IntegerField() messages = models.TextField()
项目INSTALLED_APPS配置
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'authentication.apps.AuthenticationConfig', 'chat.apps.ChatConfig' ]
authentication应用models.py代码
from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): bio = models.CharField(max_length=500) profile_picture = models.ImageField(upload_to='profile_pictures/')
chat应用serializers.py代码
from rest_framework import serializers from .models import ChatRoom from chat_app_backend.authentication.serializers import UserSerializer class ChatRoomSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) class Meta: model = ChatRoom fields = ['id', 'owner', 'picture', 'number_of_users', 'messages']
项目文件结构
chat_app_backend -chat_app_backend -authentication -chat -chat_app_backend
已尝试操作
曾参考Stack Overflow相关方案,但问题未得到解决。
解决方案
问题根源在于导入路径错误:authentication和chat是同级的Django应用,直接通过应用名导入即可,无需添加外层的chat_app_backend前缀。
1. 修改chat应用models.py的导入语句
替换原导入代码:
from chat_app_backend.authentication.models import User
为:
from authentication.models import User
2. 修改chat应用serializers.py的导入语句
替换原导入代码:
from chat_app_backend.authentication.serializers import UserSerializer
为:
from authentication.serializers import UserSerializer
可选优化方案
如果你的项目中已经在settings.py配置了AUTH_USER_MODEL = 'authentication.User',推荐使用Django提供的get_user_model()方法导入自定义用户模型,这种方式更灵活,避免硬编码应用名称:
from django.contrib.auth import get_user_model User = get_user_model()
内容的提问来源于stack exchange,提问作者sneaky dude
相关产品推荐
相关产品推荐

