django 在djanog rest框架中不显示可浏览的API接口

u1ehiz5o  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(128)

在django rest_framework中不显示可浏览的API接口
http://127.0.0.1:8000/api这是我的代码
models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser,BaseUserManager,PermissionsMixin

class CustomUserManager(BaseUserManager):
    def create_user(self,email,password=None,**extra_fields):
        if not email:
            raise ValueError('The Email Field must be set')
        email = self.normalize_email(email)
        user = self.model(email=email,**extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    def create_superuser(self,email,password=None,**extra_fields):
        extra_fields.setdefault('is_staff',True)
        extra_fields.setdefault('is_superuser',True)
        return self.create_user(email,password,**extra_fields)
class CustomUser(AbstractBaseUser,PermissionsMixin):
    email = models.EmailField(unique=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name','last_name']

    def __str__(self):
        return self.email

serializers.py

from rest_framework import serializers
from .models import CustomUser

class CustomUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ('id','email','first_name','last_name','is_active','is_staff')

views.py

from rest_framework import generics,permissions,status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from .serializers import CustomUserSerializer

class RegistrationAPIView(APIView):
    def post(self,request):
        serializer = CustomUserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            refresh = RefreshToken.for_user(user)
            return Response(
                {
                    "refresh": str(refresh),
                    "access": str(refresh.access_token),
                },
                status=status.HTTP_201_CREATED,
            )
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
 
   
class LoginAPIView(APIView):
    def post(self,request):
        email = request.data.get("email")
        password = request.data.get("password")
        user = authenticate(request, email=email,password=password)
        if user:
            login(request,user)
            refresh = RefreshToken.for_user(user)
            return Response(
                {
                    "refresh":str(refresh),
                    "access": str(refresh.access_token),
                },
                status=status.HTTP_200_OK
            )
        return Response({"error":"Invalid Credentials"},status=status.HTTP_401_UNAUTHORIZED)
@method_decorator(login_required,name="dispatch")      
class LogoutAPIView(APIView):
    def post(self,request):
        logout(request)
        return Response({"message":"Logged out Successfully"}, status=status.HTTP_200_OK)

urls.py

from django.urls import path
from .views import RegistrationAPIView,LoginAPIView,LogoutAPIView

urlpatterns=[
    path('register/',RegistrationAPIView.as_view,name="register"),
    path('login/',LoginAPIView.as_view,name='login'),
    path('logout/',LogoutAPIView.as_view,name='logout'),
]

urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/',include('auth_app.urls')),
    ]

请有人帮助解决这个问题无法找到问题在哪里我试图用django rest_framework构建身份验证API,然后用react消费它,但我面临着这个问题,无法解决这个问题。

xqk2d5yq

xqk2d5yq1#

我把as_view改成了这个as_view()

from django.urls import path
from .views import RegistrationAPIView,LoginAPIView,LogoutAPIView

urlpatterns=[
    path('register/',RegistrationAPIView.as_view(),name="register"),
    path('login/',LoginAPIView.as_view(),name='login'),
    path('logout/',LogoutAPIView.as_view(),name='logout'),
]

知道

api/register
api/login

这是显示可浏览的界面,但仍然为什么我没有得到可浏览的界面在

http://127.0.0.1:8000/api
s3fp2yjn

s3fp2yjn2#

将“rest_framework”添加到settings.py文件下的WEELED_APPS。

INSTALLED_APPS = [
   ...,
   'rest_framework',
   ...,
]

如果你已经这样做了。您可能已经更改了渲染器设置。要显示BrowsableAPI,您需要在项目设置中将BrowsableAPIRenderer保留在DEFAULT_RENDERER_CLASSES下。
Django Rest Framework自带以下默认渲染器:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

相关问题