英文:
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)
。
这是终端中的输出。
那么这里出了什么问题?是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 "fields = values" 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 '555' it executes the `else` statement as `queryset` returns `false`. But whenever I gave it the **correct** value of '123', 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('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':'User Verified'}, status=status.HTTP_202_ACCEPTED)
else:
return Response({'Login Failed':'User not registered'}, status=status.HTTP_404_NOT_FOUND)
return Response({'Bad request':'Data failed to submit'}, 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 '123' it gives me the `HTTP_400_BAD_REQUEST`. Whenever I entered something else for example '555', it gives me the `HTTP_404_NOT_FOUND` response which means the `else` statement works.
This is what I've tried so far:
First is to print out to check which block of code that isn't executed when I passed in the correct value of pengerja_id = '123' from my database.
class AuthorizeMemberView(APIView):
serializer_class = AuthorizeMemberSerializer
def post(self, request, format=None):
print(f'serializer_class={self.serializer_class}') # 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('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('Checking queryset exists()')
print(queryset.query)
if queryset.exists():
print("User Verified")
return Response({'Success':'User Verified'}, status=status.HTTP_202_ACCEPTED)
else:
print('not found')
return Response({'Login Failed':'User not registered'}, status=status.HTTP_404_NOT_FOUND)
return Response({'Bad request':'Data failed to submit'}, status=status.HTTP_400_BAD_REQUEST)
Everything from `print(serializer.is_valid())` below is not executed. But if I gave in the value of '555'(wrong value) everything is executed until return `Response({'Login Failed':'User not registered'}, status=status.HTTP_404_NOT_FOUND)`.
Here is the output in the terminal.
[Value of anything else other than '123' output](https://i.stack.imgur.com/SIKSG.png)
[Value of '123' 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('pengerja_id')
nomor_telepon = serializer.data.get('nomor_telepon')
password = serializer.data.get('password')
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 = ''
# db.tempat_lahir = ''
# db.tanggal_lahir = ''
# db.status_pekerjaan = ''
# db.domisili =''
db.save()
return Response(ShowMemberSerializer(db).data, status=status.HTTP_202_ACCEPTED)
else:
return Response({'Bad request':'Data failed to submit'}, status=status.HTTP_404_NOT_FOUND)
return Response({'Bad request':'Page not valid'}, status=status.HTTP_400_BAD_REQUEST)
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('Checking queryset exists()')
print(queryset.query)
if queryset.exists():
print("User Verified")
# db = queryset[0]
# db.pengerja_id = pengerja_id
# db.password = password
return Response({'Success':'User Verified'}, status=status.HTTP_202_ACCEPTED)
else:
print('not found')
return Response({'Login Failed':'User not registered'}, status=status.HTTP_404_NOT_FOUND)
return Response({'Bad request':'Data failed to submit'}, 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论