Django-rest-framework中的POST方法中的IF语句未执行。

huangapple go评论80阅读模式
英文:

Django-rest-framework IF statement in post method is not executing

问题

I'm here to provide a translation of the code you've provided, excluding the code itself. Here's the translation:

**(I will provide full code at the bottom)**

我正在尝试使用Django Rest Framework创建API视图。我想创建一个登录API,所以我首先在数据库中检查字段中的数据是否存在。这些是我想检查是否存在于数据库中的字段和值:

- `pengerja_id` = 123 ***//正确的数据***

- `password` = 123

现在,例如,我想尝试输入错误的值:

- `pengerja_id` = 555 ***//错误的数据***

- `password` = 555

现在,我运行了一个`if queryset.exists()`语句。每当我为`pengerja_id`提供了**错误**值,比如'555',它会执行`else`语句,因为`queryset`返回`false`。但是,每当我提供了**正确**值'123'时,它无法执行从`if serializer.is_valid()`开始的**整个**代码。

这是**view.py**中的代码:

```python
class AuthorizeMemberView(APIView):
    serializer_class = AuthorizeMemberSerializer

    def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            pengerja_id = serializer.data.get('pengerja_id')
            password = serializer.data.get('password')
            print(f'pengerja_id={pengerja_id}, password={password}')
            
            queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id=pengerja_id)

            if queryset.exists():
                return Response({'Success':'用户已验证'}, status=status.HTTP_202_ACCEPTED)
            else:
                return Response({'登录失败':'用户未注册'}, status=status.HTTP_404_NOT_FOUND)
            
        return Response({'错误请求':'数据未提交'}, status=status.HTTP_400_BAD_REQUEST)

这是serializers.py中的代码:

class AuthorizeMemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = COOL_YOUTH_MEMBER
        fields = ('pengerja_id', 'password')

结果是,每当我输入'123'时,它会给我HTTP_400_BAD_REQUEST。每当我输入其他值,例如'555',它会给我HTTP_404_NOT_FOUND的响应,这意味着else语句起作用。

这是我到目前为止尝试过的:

首先,我打印出来以检查当我从数据库中传递了pengerja_id = '123'的正确值时,哪个代码块没有执行。

class AuthorizeMemberView(APIView):
    serializer_class = AuthorizeMemberSerializer

    def post(self, request, format=None):
        print(f'serializer_class={self.serializer_class}') # 这个被执行
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            print(serializer.is_valid()) # 这个没有被执行
            pengerja_id = str(serializer.data.get('pengerja_id'))
            password = serializer.data.get('password')
            print(f'pengerja_id={pengerja_id}, password={password}')
            
            queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id=pengerja_id)
            print('检查queryset是否存在()')
            print(queryset.query)
            if queryset.exists():
                print("用户已验证")
                return Response({'成功':'用户已验证'}, status=status.HTTP_202_ACCEPTED)
            else:
                print('未找到')
                return Response({'登录失败':'用户未注册'}, status=status.HTTP_404_NOT_FOUND)
            
        return Response({'错误请求':'数据未提交'}, status=status.HTTP_400_BAD_REQUEST)

print(serializer.is_valid())以下的所有内容都没有执行。但如果我提供值'555'(错误的值),则一切都会执行,直到返回Response({'登录失败':'用户未注册'}, status=status.HTTP_404_NOT_FOUND)

这是终端中的输出。

任何不是'123'的值的输出

'123'的值的输出

那么这里出了什么问题?是Django有什么bug,还是我漏掉了什么?

这是下面的完整代码

models.py

from django.db import models
import mysql.connector

# 创建你的模型
class COOL_YOUTH_MEMBER(models.Model):
    pengerja_id = models.CharField(max_length=255, unique=True, primary_key=True)
    nomor_telepon = models.CharField(max_length=255, unique=True)
    password = models.CharField(max_length=255)
    nama_cool = models.CharField(max_length=255)
    tempat_lahir = models.CharField(max_length=255)
    tanggal_lahir = models.DateField(null=True)
    status_pekerjaan = models.CharField(max_length=255)
    domisili = models.CharField(max_length=255)
    user_session_key = models.CharField(max_length=255, null=True)

serializers.py

from rest_framework import serializers
from .models import COOL_YOUTH_MEMBER

class AuthorizeMemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = COOL_YOUTH_MEMBER
        fields = ('pengerja_id', 'password')

views.py

from django.shortcuts import render
from django.contrib.auth.backends import BaseBackend
from rest_framework import generics, status
from .serializers import ( 
                    ShowMemberSerializer,
                    InsertNewMemberSerializer,
                    AuthorizeMemberSerializer
                    )
from .models import COOL_YOUTH_MEMBER
from rest_framework.views import APIView
from rest_framework.response import Response

# 创建你的视图
class ShowMemberView(generics.ListAPIView):
    queryset = COOL_YOUTH_MEMBER.objects.all()
    serializer_class = ShowMemberSerializer

class AuthorizeMemberView(APIView):
    serializer_class = AuthorizeMemberSerializer

    def post(self, request, format=None):
        print(f'serializer_class={self.serializer_class}')
        serializer = self.serializer_class(data=request.data)
        if serializer is_valid():
            print(serializer.is_valid())
            pengerja_id = str(serializer.data.get('pengerja_id'))
            password = serializer.data.get('password')
            print(f'pengerja_id={pengerja_id}, password={password}')
            
            queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id=pengerja_id)
            print('检查queryset是否存在()')
            print(queryset.query)
            if queryset.exists():
                print("用户已验证")
                return Response({'成功':'用户已验证'}, status=status.HTTP_202_ACCEPTED)
            else:
                print('未找到')
                return Response({'登录失败

<details>
<summary>英文:</summary>

**(I will provide full code at the bottom)**  
  
I am trying to create an API view with django rest framework. I wanted to create a login API so I was first testing out on how to check if a data exists in a field in the database. Here are the &quot;fields = values&quot; that I want to check that actually exists in the database:

- `pengerja_id` = 123 ***//correct data***

- `password` = 123

Now for example I want to try inputting the wrong value:

- `pengerja_id` = 555 ***//wrong data***

- `password` = 555

Now, I run an `if queryset.exists()` statement. Whenever I gave `pengerja_id` a **wrong** value like &#39;555&#39; it executes the `else` statement as `queryset` returns `false`. But whenever I gave it the **correct** value of &#39;123&#39;, It fails to execute the **WHOLE** code for some reason starting from if `serializer.is_valid()`.

Here is the code inside **view.py**

class AuthorizeMemberView(APIView):
serializer_class = AuthorizeMemberSerializer

def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
pengerja_id = serializer.data.get(&#39;pengerja_id&#39;)
password = serializer.data.get(&#39;password&#39;)
print(f&#39;pengerja_id={pengerja_id}, password={password}&#39;)
queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id = pengerja_id)
if queryset.exists():
return Response({&#39;Success&#39;:&#39;User Verified&#39;}, status=status.HTTP_202_ACCEPTED)
else:
return Response({&#39;Login Failed&#39;:&#39;User not registered&#39;}, status=status.HTTP_404_NOT_FOUND)
return Response({&#39;Bad request&#39;:&#39;Data failed to submit&#39;}, status=status.HTTP_400_BAD_REQUEST)

Here is the code inside **serializers.py**

class AuthorizeMemberSerializer(serializers.ModelSerializer):
class Meta:
model = COOL_YOUTH_MEMBER
fields = ('pengerja_id', 'password')


The results are whenever I entered &#39;123&#39; it gives me the `HTTP_400_BAD_REQUEST`. Whenever I entered something else for example &#39;555&#39;, it gives me the `HTTP_404_NOT_FOUND` response which means the `else` statement works.
This is what I&#39;ve tried so far:
First is to print out to check which block of code that isn&#39;t executed when I passed in the correct value of pengerja_id = &#39;123&#39; from my database.

class AuthorizeMemberView(APIView):
serializer_class = AuthorizeMemberSerializer

def post(self, request, format=None):
print(f&#39;serializer_class={self.serializer_class}&#39;) # this is executed
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
print(serializer.is_valid()) # this is not executed
pengerja_id = str(serializer.data.get(&#39;pengerja_id&#39;))
password = serializer.data.get(&#39;password&#39;)
print(f&#39;pengerja_id={pengerja_id}, password={password}&#39;)
queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id = pengerja_id)
print(&#39;Checking queryset exists()&#39;)
print(queryset.query)
if queryset.exists():
print(&quot;User Verified&quot;)
return Response({&#39;Success&#39;:&#39;User Verified&#39;}, status=status.HTTP_202_ACCEPTED)
else:
print(&#39;not found&#39;)
return Response({&#39;Login Failed&#39;:&#39;User not registered&#39;}, status=status.HTTP_404_NOT_FOUND)
return Response({&#39;Bad request&#39;:&#39;Data failed to submit&#39;}, status=status.HTTP_400_BAD_REQUEST)

Everything from `print(serializer.is_valid())` below is not executed. But if I gave in the value of &#39;555&#39;(wrong value) everything is executed until return `Response({&#39;Login Failed&#39;:&#39;User not registered&#39;}, status=status.HTTP_404_NOT_FOUND)`.
Here is the output in the terminal.
[Value of anything else other than &#39;123&#39; output](https://i.stack.imgur.com/SIKSG.png)
[Value of &#39;123&#39; ouput](https://i.stack.imgur.com/Z9OCW.png)
So what went wrong here? Is it some kind of bug that django has or am I missing something here?
**This is the full code below**
**models.py**

from django.db import models
import mysql.connector

Create your models here.

class COOL_YOUTH_MEMBER(models.Model):
pengerja_id = models.CharField(max_length=255, unique=True, primary_key=True)
nomor_telepon = models.CharField(max_length=255, unique=True)
password = models.CharField(max_length=255)
nama_cool = models.CharField(max_length=255)
tempat_lahir = models.CharField(max_length=255)
tanggal_lahir = models.DateField(null=True)
status_pekerjaan = models.CharField(max_length=255)
domisili = models.CharField(max_length=255)
user_session_key = models.CharField(max_length=255, null=True)


**serializers.py**

from rest_framework import serializers
from .models import COOL_YOUTH_MEMBER

class ShowMemberSerializer(serializers.ModelSerializer):
class Meta:
model = COOL_YOUTH_MEMBER
fields = ('pengerja_id','nomor_telepon','password','nama_cool','tempat_lahir',
'tanggal_lahir', 'status_pekerjaan', 'domisili', 'user_session_key')

class InsertNewMemberSerializer(serializers.ModelSerializer):
class Meta:
model = COOL_YOUTH_MEMBER
fields = ('pengerja_id','nomor_telepon','password')
# ,'nama_cool','tempat_lahir',
# 'tanggal_lahir', 'status_pekerjaan', 'domisili')

class AuthorizeMemberSerializer(serializers.ModelSerializer):
class Meta:
model = COOL_YOUTH_MEMBER
fields = ('pengerja_id', 'password')


**views.py**

from django.shortcuts import render
from django.contrib.auth.backends import BaseBackend
from rest_framework import generics, status
from .serializers import (
ShowMemberSerializer,
InsertNewMemberSerializer,
AuthorizeMemberSerializer
)
from .models import COOL_YOUTH_MEMBER
from rest_framework.views import APIView
from rest_framework.response import Response

Create your views here.

def index(request, *args, **kwargs):

return render(request, index.html)

class ShowMemberView(generics.ListAPIView):
queryset = COOL_YOUTH_MEMBER.objects.all()
serializer_class = ShowMemberSerializer

class InsertNewMemberView(APIView):
serializer_class = InsertNewMemberSerializer

def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
pengerja_id = serializer.data.get(&#39;pengerja_id&#39;)
nomor_telepon = serializer.data.get(&#39;nomor_telepon&#39;)
password = serializer.data.get(&#39;password&#39;)
queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id = pengerja_id)
if not queryset.exists():
db = COOL_YOUTH_MEMBER(
pengerja_id = pengerja_id,
nomor_telepon = nomor_telepon,
password = password,
)
# db.nama_cool = &#39;&#39;
# db.tempat_lahir = &#39;&#39;
# db.tanggal_lahir = &#39;&#39;
# db.status_pekerjaan = &#39;&#39;
# db.domisili =&#39;&#39;
db.save()
return Response(ShowMemberSerializer(db).data, status=status.HTTP_202_ACCEPTED)
else:
return Response({&#39;Bad request&#39;:&#39;Data failed to submit&#39;}, status=status.HTTP_404_NOT_FOUND)
return Response({&#39;Bad request&#39;:&#39;Page not valid&#39;}, status=status.HTTP_400_BAD_REQUEST)

class AuthorizeMemberView(APIView):
serializer_class = AuthorizeMemberSerializer

def post(self, request, format=None):
print(f&#39;serializer_class={self.serializer_class}&#39;)
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
print(serializer.is_valid())
pengerja_id = str(serializer.data.get(&#39;pengerja_id&#39;))
password = serializer.data.get(&#39;password&#39;)
print(f&#39;pengerja_id={pengerja_id}, password={password}&#39;)
queryset = COOL_YOUTH_MEMBER.objects.filter(pengerja_id = pengerja_id)
print(&#39;Checking queryset exists()&#39;)
print(queryset.query)
if queryset.exists():
print(&quot;User Verified&quot;)
# db = queryset[0]
# db.pengerja_id = pengerja_id
# db.password = password
return Response({&#39;Success&#39;:&#39;User Verified&#39;}, status=status.HTTP_202_ACCEPTED)
else:
print(&#39;not found&#39;)
return Response({&#39;Login Failed&#39;:&#39;User not registered&#39;}, status=status.HTTP_404_NOT_FOUND)
return Response({&#39;Bad request&#39;:&#39;Data failed to submit&#39;}, status=status.HTTP_400_BAD_REQUEST)

**urls.py**

from django.urls import path
from .views import (
ShowMemberView,
InsertNewMemberView,
AuthorizeMemberView,
)

urlpatterns = [
path('show', ShowMemberView.as_view()),
path('new-member', InsertNewMemberView.as_view()),
path('authorize', AuthorizeMemberView.as_view()),
]

Also the class `InsertNewMemberView` works just fine. Code is almost the same.
</details>
# 答案1
**得分**: 0
在 `if serializer.is_valid()` 之前,尝试这个以了解错误信息:
```python
print(serialzer.errors)

它将返回一个带有错误信息的字典。

英文:

Before if serializer.is_valid() try this to know what the error is:

print(serialzer.errors)

It will return a dictionary with the errors

huangapple
  • 本文由 发表于 2023年2月27日 17:08:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定