我正在编写基于Django(2.2.2)和Django Rest Framework(3.9.4)的API。 目标是创建简单的消息系统。 创建用于创建消息的端点后,出现TypeError:
TypeError at /api/v1/message/create/
__str__ returned non-string (type Message)
The 'message_body' in the DB contains PL characteristic characters.
我为序列化器尝试了serializer.Serializer和serializer.ModelSerializer,为视图尝试了CreateAPIView和ListCreateAPIView。 真正有趣的是,用于列出消息的端点工作正常。
这几乎是我的其他终结点(也就是CreateAPIView)的复制粘贴代码,其工作正常。
我还在 str (自身)上尝试了一些编码方法,但猜测不正确。
{
"model": "core.message",
"pk": 1,
"fields": {
"chat": 1,
"message_body": "Wiadomość testowa 1",
"sender": "user",
"sent": "2019-05-05T10:20:37+01:00",
"is_viewed": true
}
}
class Message(models.Model):
"""
Model representing single message in DB
"""
chat = models.ForeignKey(
'Chat',
on_delete=models.CASCADE,
unique=False
)
message_body = models.TextField(blank=False, null=False)
sender = models.CharField(max_length=4)
sent = models.DateTimeField(auto_now_add=True)
is_viewed = models.BooleanField(default=False)
def __unicode__(self):
return self.message_body
def __str__(self):
return self.message_body.decode('utf8')
from rest_framework import generics, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from message.serializers import (
ListMessageSerializer,
CreateMessageSerializer
)
from core.models import Message
class CreateMessageView(generics.CreateAPIView):
"""
Create new message view
"""
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
serializer_class = CreateMessageSerializer
def perform_create(self, serializer):
"""
Save data to DB, if valid
"""
if serializer.is_valid():
serializer.save()
else:
return Response(
serializer.errors,
status.HTTP_400_BAD_REQUEST
)
from rest_framework import serializers
from core.models import Chat, Message
class CreateMessageSerializer(serializers.ModelSerializer):
"""
Serializer for creating ne message
"""
class Meta:
model = Message
fields = (
'id',
'chat',
'message_body',
'sender',
'sent',
'is_viewed'
)
read_only_field = ('id',)
def validate(self, attrs):
"""
Validate request data
"""
message_body = attrs.get('message_body')
if not message_body or message_body is None:
msg = _('Can\'t send empty message!')
raise serializers.ValidationError(msg, code='authentication')
return attrs
def create(self, validated_data):
"""
Insert Message into DB
"""
return Message.objects.create(**validated_data)
from django.urls import path
from message import views
app_name = 'message'
urlpatterns = [
path('create/', views.CreateMessageView.as_view(), name='create'),
]
我希望能够在浏览器中打开以下视图: api / v1 / message / create / 并手动测试创建新消息:)
答案 0 :(得分:0)
我删除了以下主键之间的重新关联: 聊天-DB中消息的父级
现在一切正常:)