python - Rest_framework导入问题

标签 python django-rest-framework

我正在尝试实现 django Rest 框架。我遇到这个错误:

File "F:\....\urls.py", line 19, in <module>
    from Userinfo import views
File "F:\....\Userinfo\views.py", line 8, in <module>
    from .serializers import usersSerializer
File "F:\.....\Userinfo\serializers.py", line 2, in <module>
    from rest_framework import users
ImportError: cannot import name 'users' from 'rest_framework' (C:\Users\....\rest_framework\__init__.py)

我的 urls.py 代码:

from django.contrib import admin
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from Userinfo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('UserData', views.UserList.as_view()),
]*

我的views.py代码:

from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import users
from .serializers import usersSerializer

class UserList(APIView):
    def get(self, request):
         user1 = users.objects.all()
         serializer = usersSerializer(user1, many = True)
         return Response(serializer.data)*

我的serializers.py代码:

 from rest_framework import serializers
 from rest_framework import users
 class usersSerializer(Serializers.ModelSerializer):
 class Meta:
    model = users
    fields = '__all__'*

我的 models.py 代码:

from django.db import models

class users(models.Model):
   Name = models.CharField(max_length=50)
   id = models.IntegerField(primary_key=True)
   DocumentCount = models.IntegerField()
   Role = models.CharField(max_length=15)
def _str_(self):
   return self.name + self.id*

代码可能不完整,但我会提供尽可能多的信息。

最佳答案

在你的serializers.py中:

from rest_framework import serializers
# from rest_framework import users # remove this
from django.contrib.auth import get_user_model # add this

User = get_user_model()

class usersSerializer(Serializers.ModelSerializer):

    class Meta:
        model = Users
        # model = get_user_model() # this will work too
        fields = '__all__'

关于python - Rest_framework导入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66461459/

相关文章:

python - matplotlib 中的命名颜色

python - Discord 制作一个笑话机器人

python - Django REST Framework : Disable migration of all built in schemas, 即(auth.contenttypes.admin.等)

python - 如何覆盖 Django Rest Framework Serializer 中的验证?

python - 如何重命名 django rest_framework 的 search_fields 中的字段?

python - 退出 root conda 环境

python - Pandas pivot_table,按列对值进行排序

python - MATLAB "The command is too long to execute"错误怎么办?

Django休息框架: Correct way to override perform_create in ModelViewSet?

django - 无法将目标WSGI脚本'/var/www/backend/backend/wsgi.py'加载为Python模块