I'm creating a chat demo using SwampDragon and I'm unsure how to create a model with related fields.
Using the code below, an error occurs each time I call the createMessage
function in javascript. The only error I receive is from the websocket output: c[3001,"Connection aborted"]
. There is no output on the python console to shed any extra light on this error.
Can anyone help me understand how to create a Message
, with the related field of User
?
Model:
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)
Serializer:
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', )
Route:
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);
});
},
...
Requirements
- django==1.7.6
- SwampDragon==0.4.1.2
- SwampDragon-auth==0.1.3
To answer my own question: This is not built into the framework as I expected. You need to instantiate the related models in the router in the
get_initial
method. These will then be passed to the serializer and will create theMessage
model correctly.Route
Javascript
Serializer