Python ModuleNotFoundError:我无法导入模块

时间:2020-06-14 14:11:58

标签: python django django-rest-framework

我有一个CRUD应用,我正在学习Python和Django的API休息...我创建了这个模块:

from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model: User
    fields = ['url', 'username', 'email', 'groups']

然后,我这样写:

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from djangoCRUD.Api.serializer import UserSerializer


class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""

   queryset = User.objects.all().orderby('-date_joined')
   serializer_class = UserSerializer

没关系,但是,当我在这里写url.py时,我遇到了问题:

from django.contrib import admin
from django.urls import path, include

from rest_framework import routers
from djangoCRUD.Api import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include(router.urls)),
   path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

我有此错误消息:

文件“ C:\ PythonDev \ pythoncrud \ venv \ djangoCRUD \ djangoCRUD \ urls.py”,第20行,在 从djangoCRUD.Api导入视图 ModuleNotFoundError:没有名为“ djangoCRUD.Api”的模块

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

from django.contrib import admin
from django.urls import path, include

from rest_framework import routers
# from djangoCRUD.Api import views
from djangoCRUD.Api.views import UserViewSet

router = routers.DefaultRouter()
# router.register(r'users', views.UserViewSet)
router.register(r'users', UserViewSet)

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include(router.urls)),
   path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]