Search code examples
pythondjangourlpathproject

Django ViewSet ModuleNotFoundError: No module named 'project name'


I'm trying to use the ModelViewSet to display Users, but for some reason Django does not seem to like the UserViewSet import in project/urls.py. Seems like a pretty silly error, but I've been stuck on this for a while and it's frustrating. I don't have any errors in the code as far as I know and the imports are fully functional. Am I missing something?

Django version 2.2.13

project/urls.py

from django_backend.user_profile.views import UserViewSet

router = routers.DefaultRouter()
router.register('user', UserViewSet)

urlpatterns = [
    path('accounts/', include(router.urls)),
]

userprofile/views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()#.order_by('-date_joined')
    serializer_class = UserSerializer

Error

from django_backend.user_profile.views import UserViewSet
ModuleNotFoundError: No module named 'django_backend'

Project structure

enter image description here


Solution

  • From the comments, we figured out the direct answer to your question is this: You're importing django_backend, which is the root of your project, but isn't a formal Python package that exists in sys.path and thus cannot be imported as such.

    Since Django sets sys.path to your project's root directory, you'll want to import user_profile.views without the django_backend part:

    from user_profile.views import UserViewSet
    

    Once you do that, you might consider configuring PyCharm to know that the django_backend folder is your Sources Root. That will tell PyCharm where to look for Python code, so that it doesn't show an error attempting to import modules from your Django directory.