[Answered ]-ModuleNotFoundError: No module named 'chat_app_backend.authentication' in Django project

1๐Ÿ‘

โœ…

You import this with:

from authentication.models import User

But it is usually better to make use of the settings.AUTH_USER_MODELย [Django-doc] to refer to the user model. Indeed, in the settings you specify this as:

# settings.py

AUTH_USER_MODEL = 'authentication.User'

and then use the settings instead:

from django.conf import settings
from django.db import models


class ChatRoom(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    # โ€ฆ

Regardless what option you decide, likely you have set the "source root" in your IDE on the wrong directory. This should be the chat_app_backend in the chat_app_backend. It might also be better to give the directories a different name, especially if a directory or file has the same name as its parent directory, this can introduce a lot of confusion.

0๐Ÿ‘

try this:

import os
import sys

# Add the chat_app_backend directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from chat_app_backend.authentication.models import User

os.path.abspath(__file__) gives you the absolute path of the current file which is models.py. Then os.path.dirname() function returns the directory containing the file which here is chat directory. Finally we use sys.path.append() to add it to the Python path.

๐Ÿ‘คPhoenix

Leave a comment