我试图创建一个应用程序,用户可以登录和创建任务。我的django应用程序的代码托管在here上
我使用JWT身份验证和drf-yasg来生成swagger。因此TaskSerializer接受3个参数
- taskname是字符串
- 布尔型完成
- username,应指向用户模型
我的TaskModel
如下
class Tasks(models.Model):
taskname=models.CharField(max_length=10)
completion=models.BooleanField(default=False)
username = models.ForeignKey(User, on_delete=models.CASCADE)
字符串
我的TaskSerializer
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Tasks
fields = ['taskname', 'completion', 'username']
型
我的TaskView
如下:
class TaskView(APIView):
def get(self, request):
token = request.COOKIES.get('jwt')
if not token:
raise AuthenticationFailed('Unauthenticated!')
try:
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationFailed('Unauthenticated!')
tasks = Tasks.objects.filter(username=payload['username']).all()
return Response(tasks)
@swagger_auto_schema(
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'taskname': openapi.Schema(type=openapi.TYPE_STRING, description='Add taskname'),
'completion': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='completion'),
}
)
)
def post(self, request):
token = request.COOKIES.get('jwt')
if not token:
raise AuthenticationFailed('Unauthenticated!')
try:
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise AuthenticationFailed('Unauthenticated!')
req_data = {
"username": User.objects.filter(username=payload['username']).first(),
"taskname": request.data['taskname'],
"completion": request.data['completion'],
}
print(5*'*', req_data)
serializer = TaskSerializer(
data=request.data
)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
型
然而,当我创建一个任务,我可以从令牌中检索用户,并通过swagger将post请求发送到/task
时,我得到以下错误:
{
"username": [
"This field is required."
]
}
型
1条答案
按热度按时间jgovgodb1#
你正在发送错误的数据到序列化器。它应该像这样:
字符串