简体   繁体   English

如何使用django-rest-framework创建Login视图

[英]How do I create a Login view with django-rest-framework

I have a serializer and a view for my login like this. 我有一个序列化程序和我的登录视图这样。

class LoginView(generics.RetrieveAPIView):
    serializer_class= LoginSerializer
    queryset=User.objects.all()

    error_messages = {
        'invalid': "Invalid username or password",
        'disabled': "Sorry, this account is suspended",
    }

    def _error_response(self, message_key):
        data = {
            'success': False,
            'message': self.error_messages[message_key],
            'user_id': None,
        }
    def post(self,request):
        email = request.POST.get('email')
        password = request.POST.get('password')
        user = authenticate(email=email, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)

                return Response(status=status.HTTP_100_OK)
            return self._error_response('disabled')
        return self._error_response('invalid')

and the serializer: 和序列化器:

class LoginSerializer(serializers.ModelSerializer):
     class Meta:
         model=User
         fields=('email','password') 

My url: 我的网址:

(r'^login/$',LoginView.as_view())

When I run the code I get an error ImproperlyConfigured at /login/ Expected view LoginView to be called with a URL keyword argument named "pk". 当我运行代码时,我得到一个错误ErrorperlyConfigured at / login / Expected view LoginView用一个名为“pk”的URL关键字参数调用。 Fix your URL conf, or set the .lookup_field attribute on the view correctly. 修复您的URL conf,或正确设置视图上的.lookup_field属性。

I currently do not have redirecting in my view. 我目前没有在我看来重定向。 what have I done wrong? 我做错了什么?

You are used generic.RetrieveAPIView which extends RetrieveModelMixin and GenericAPIView , as per docs it need pk or you have to set .lookup_field in your class. 你使用generic.RetrieveAPIView扩展了RetrieveModelMixinGenericAPIView ,根据它需要pk文档或你必须在你的类中设置.lookup_field

RetrieveAPIView is used to get and get means retrieve data and to retrieve data it need pk . RetrieveAPIView用于getget检索数据并检索它需要pk数据。

Use another class to handle your POST 使用另一个类来处理您的POST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM