python - 注册和登录 api 中的 Django Rest 框架

标签 python django django-rest-framework

我是 Django 初学者

Git Repo

我正在创建注册和登录API,并且我还创建了注册API,这没有任何问题,但是我对登录API一无所知,所以我得到了一个错误,在我看来,< strong>serializers.py 和 views.py 中有一个小错误,请告诉我错误,以便我知道错误在哪里。

File "/Users/sierra/Courses/LoginAPI/form/serializers.py",line 14

if Account.objects.filter(email=email,password=password).exists() :
TabError: inconsistent use of tabs and spaces in indentationBlockquote

序列化器.py

from rest_framework import serializers

from form.models import Account

# from django.contrib.auth.models import User

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

        extra_kwargs = {'password': {'write_only': True}}

        if Account.objects.filter(email=email,password=password).exists() :
            return True

        return False

    # def validate(self, data):
    #   password = data.get('password')
    #   email = data.get('email')


    # def username_present(email,password):




class RegistrationSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = Account
        fields = ['email', 'username', 'password', 'password2']
        extra_kwargs = {
                'password': {'write_only': True},
        }


    def save(self):

        account = Account(
                    email=self.validated_data['email'],
                    username=self.validated_data['username']
                )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match.'})
        account.set_password(password)
        account.save()
        return account

views.py

from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from form.serializers import RegistrationSerializer


@api_view(['POST', ])
def registration_view(request):

    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = 'successfully registered new user.'
            data['email'] = account.email
            data['username'] = account.username
        else:
            data = serializer.errors
        return Response(data)

@api_view(['POST,'])
def login_view(request):

    if request.method == 'POST':
        serializer = LoginSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            date['response'] = 'User successfully Login'
        else:
            data['response'] = 'You have entered an invalid username or password'
        return Response(data)

最佳答案

这是您问题的正确解决方案:-

序列化器.py

from rest_framework import serializers
from rest_framework.exceptions import NotAuthenticated
from .models import register

class LoginSerializer(serializers.ModelSerializer):

class Meta:
    model = register
    fields = ['username', 'password',]
    extra_kwargs = {'password': {'write_only': True}}

def validate(self, data):
    username = data.get("username", None)
    password = data.get("password", None)
    if register.objects.filter(username=username).filter(password=password).first():
        return True
    raise NotAuthenticated

Views.py

from rest_framework.generics import RetrieveAPIView
from rest_framework.response import Response
import utils.response_handler as rh
from .serializers import LoginSerializer

class loginview(RetrieveAPIView):
    def post(self, request):
        username=request.data.get('username')
        serializer = LoginSerializer(self,data=request.data)

        if serializer.is_valid():
            r=rh.ResponseMsg(data={
                "username":username,
            },msg="Login Successfully",error=False)
            return Response(r.response)

关于python - 注册和登录 api 中的 Django Rest 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60465021/

相关文章:

python - Django意外保存字符串元组

python - PuLP CBC 多线程不适用于 COIN_CMD

python - 如何为多个页面 URL 运行 Multi-Mechanize 性能测试 python 脚本

python - 从 Django 应用程序中排除 url 模式..这可能吗?

python - 图表js条形图上方的空间

AngularJS 从 GeoJSON 响应获取坐标

django rest 框架中的 django_countries 序列化程序

python - 使用 Tensorflow 在 Windows 10 上为 ML-Agents 设置 Unity3D 机器学习

python - 在 Python 中使用 '@patch.object' 和 'with patch.object' 有什么区别?

python - 在 Django 博客中查看作者的文章