【发布时间】:2021-07-01 06:49:43
【问题描述】:
我正在创建一个 Django-rest 身份验证 API。但是,每次我尝试创建用户时,都会收到此错误。我在这里尝试了几种解决方案,但均未成功。
HTTP 405 方法不允许 允许:POST、OPTIONS 内容类型:应用程序/json 变化:接受
{ "detail": "不允许使用方法 "GET"。" }
为什么?有什么我应该做的改变吗?
这是我的 Serializers.py
from rest_framework import serializers
from .models import CustomUser
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super(MyTokenObtainPairSerializer, cls).get_token(user)
token['fav_color'] = user.fav_color
return token
class CustomUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
username = serializers.CharField()
password = serializers.CharField(min_length = 8, write_only= True)
class Meta:
model = CustomUser
fields = ('email', 'username', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
password = validated_data.pop('password', None)
instance = self.Meta.model(**validated_data)
if password is not None:
instance.set_password(password)
instance.save()
return instance
这是我的 Views.py
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework.views import APIView
from rest_framework import permissions
from rest_framework.response import Response
from .serializers import TokenObtainPairSerializer
from .serializers import CustomUserSerializer, MyTokenObtainPairSerializer
# Create your views here.
class ObtainTokenPairWithColorView(TokenObtainPairView):
permission_classes = (permissions.AllowAny,)
serializer_class = TokenObtainPairSerializer
class CustomUserCreate(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, render, format = 'json'):
serializer = CustomUserSerializer(data= request.data)
if serializer.is_valid:
user = serializer.save()
if user:
json = serializer.data
return Response(status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class HelloWorld(APIView):
def get(self, request):
return Response(data={"hello":"world"}, status=status.HTTP_200_OK)
【问题讨论】:
-
为什么在 CustomUserSerializer 的元类中创建 def create。粘贴时是拼写错误还是您的实际代码是这样的?
-
反正错误可能是因为你在django界面选择了GET,应该是POST