Reputation: 2123
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
Upvotes: 2
Views: 2115
Reputation: 565
The python interpreter searches for modules in the directories listed in sys.path. You could quickly print sys.path to check whether 'reactjs-comeon' is listed.
Depending on how you ran your file it might not be included. For exemple if you ran project> python urls.py it wouldn't be. You can manually append the directory to sys.path as a quick solution.
In general I would recommend you read-up on relative/absolute imports and packaging on https://docs.python.org/3/reference/import.html
Upvotes: 1
Reputation: 13140
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.
Upvotes: 2