我正在使用SwampDragon创建聊天演示,但不确定如何创建具有相关字段的模型。
使用下面的代码,每次我createMessage
在 javascript 中调用该函数时都会发生错误。我收到的唯一错误来自 websocket 输出:c[3001,"Connection aborted"]
. python 控制台上没有任何输出来解释这个错误。
任何人都可以帮助我了解如何创建一个Message
相关领域的User
?
模型:
from django.contrib.auth.models import User
from django.db import models
from swampdragon.models import SelfPublishModel
from .serializers import MessageSerializer
class Message(SelfPublishModel, models.Model):
serializer_class = MessageSerializer
user = models.ForeignKey(User, related_name='messages')
body = models.TextField(blank=True)
序列化器:
from swampdragon.serializers.model_serializer import ModelSerializer
from django.contrib.auth.models import User
class UserSerializer(ModelSerializer):
class Meta:
model = User
publish_fields = ('id', 'username')
update_fields = ('first_name', 'last_name', )
class MessageSerializer(ModelSerializer):
user = UserSerializer
class Meta:
model = b'chat.Message'
publish_fields = ('body', 'user', )
update_fields = ('body', 'user', )
路线:
from swampdragon import route_handler
from swampdragon.route_handler import ModelRouter, BaseRouter
from .models import Message
from .serializers import MessageSerializer, UserSerializer
class MessageRouter(ModelRouter):
route_name = 'message'
serializer_class = MessageSerializer
model = Message
include_related = [UserSerializer, ]
def get_object(self, **kwargs):
return self.model.objects.get(pk=kwargs['id'])
def get_query_set(self, **kwargs):
return self.model.objects.all()
route_handler.register(MessageRouter)
Javascipt:
...
createMessage: function(message){
var data = {
user: 1,
body: message
};
swampdragon.create('message', data, function (context, data) {
console.log('MessageStore: onCreate success.', context, data);
}, function (context, data) {
console.log('MessageStore: onCreate failed.', context, data);
});
},
...
要求
- django==1.7.6
- 沼泽龙==0.4.1.2
- SwampDragon-auth==0.1.3