Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django通道非空约束失败:chat_chatmessage.message_Python_Django_Django Views_Django Channels - Fatal编程技术网

Python Django通道非空约束失败:chat_chatmessage.message

Python Django通道非空约束失败:chat_chatmessage.message,python,django,django-views,django-channels,Python,Django,Django Views,Django Channels,我正在尝试在Django通道应用程序中完成通知系统 当我通过websocket发送消息或文本字符串时,websocket.recieve将在发送初始消息后生成大量空字符串 127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECTING /messages/trilla" - - connected {'type': 'websocket.connect'} 127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "W

我正在尝试在Django通道应用程序中完成通知系统

当我通过websocket发送消息或文本字符串时,
websocket.recieve
将在发送初始消息后生成大量空字符串

127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECTING /messages/trilla" - -
connected {'type': 'websocket.connect'}
127.0.0.1:54917 - - [27/Apr/2019:19:04:05] "WSCONNECT /messages/trilla" - -
receive {'type': 'websocket.receive', 'text': '{"message":"hi there"}'}
websocket.receive
receive {'type': 'websocket.receive', 'text': '{"message":""}'}
websocket.receive
receive {'type': 'websocket.receive', 'text': '{"message":""}'}
websocket.receive
receive {'type': 'websocket.receive', 'text': '{"message":""}'}
websocket.receive
导航栏有一个JS脚本,可以添加新的通知。从服务器消息构造html字符串,然后将其插入html页面

当我点击导航栏通知图标时,我得到的
非空约束失败:chat\u chatmessage.message
。我假设是因为空字符串问题生成了大量空消息

这是我单击通知图标时的日志

receive {'type': 'websocket.receive', 'text': '{"type":"notification_read","username":{},"notification_id":{"jQuery33100053785670652706231":{"display":""}}}'}
websocket.receive
2019-04-28 11:59:47,041 ERROR    Exception inside application: NOT NULL constraint failed: chat_chatmessage.message
很明显,数据传递不正确。我遵循了Django通道部分的教程,在尝试这么做之前没有使用JS/WebSockets的经验,因此我在查找问题代码方面的技能有限

消费者.py

async def websocket_receive(self, event):
        # when a message is recieved from the websocket
        print("receive", event)

        message_type = event.get('type', None)  #check message type, act accordingly
        print(message_type)
        if message_type == "notification_read":
            # Update the notification read status flag in Notification model.
            notification = Notification.object.get(id=notification_id)
            notification.notification_read = True
            notification.save()  #commit to DB
            print("notification read")

        front_text = event.get('text', None)
        if front_text is not None:
            loaded_dict_data = json.loads(front_text)
            msg =  loaded_dict_data.get('message')
            user = self.scope['user']
            username = 'default'
            notification_id = 'default'
            if user.is_authenticated:
                username = user.username
            myResponse = {
                'message': msg,
                'username': username,
                'notification': notification_id,
            }
            await self.create_chat_message(user, msg)

            # broadcasts the message event to be sent, the group send layer
            # triggers the chat_message function for all of the group (chat_room)
            await self.channel_layer.group_send(
                self.chat_room,
                {
                    'type': 'chat_message',
                    'text': json.dumps(myResponse)
                }
            )
    # chat_method is a custom method name that we made
    async def chat_message(self, event):
        # sends the actual message
        await self.send({
                'type': 'websocket.send',
                'text': event['text']
        })


 async def websocket_disconnect(self, event):
        # when the socket disconnects
        print('disconnected', event)

    @database_sync_to_async
    def get_thread(self, user, other_username):
        return Thread.objects.get_or_new(user, other_username)[0]

    @database_sync_to_async
    def create_chat_message(self, me, msg):
        thread_obj = self.thread_obj
        return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)
base.html

<script>
    $(document).ready(function() {
      $("#notificationLink").click(function() {
        var data = {
          "type": "notification_read",
          "username": username,
          "notification_id": notification_id,
        }
        socket.send(JSON.stringify(data));

        $("#notificationContainer").fadeToggle(300);
        $("#notification_id").fadeOut("slow");
        return false;
      });
</script>

<script>
    // websocket scripts - client side*
    var loc = window.location
    var formData = $("#form")
    var msgInput = $("#id_message")
    var chatHolder = $('#chat-items')
    var me = $('#myUsername').val()
    var notification = $("#notificationLink")

    var wsStart = 'ws://'
    if (loc.protocol == 'https:') {
      wsStart = 'wss://'
    }
    var endpoint = wsStart + loc.host + loc.pathname
    var socket = new ReconnectingWebSocket(endpoint)

    // below is the message I am receiving
    socket.onmessage = function(e) {
      var data = JSON.parse(event.data);
      // Find the notification icon/button/whatever and show a red dot, add the notification_id to element as id or data attribute.
      notification.append("<span id=#notification_id>" + notification.notification_id)

      console.log("message", e)
      var chatDataMsg = JSON.parse(e.data)
      chatHolder.append('<li>' + chatDataMsg.message + ' from ' + chatDataMsg.username + '</li>')
    }

    // below is the message I am sending
    socket.onopen = function(e) {
      console.log("open", e)
      formData.submit(function(event) {
        event.preventDefault()
        var msgText = msgInput.val()
        var finalData = {
          'message': msgText
        }
        socket.send(JSON.stringify(finalData))
        formData[0].reset()
      })
    }

$(文档).ready(函数(){
$(“#notificationLink”)。单击(函数(){
风险值数据={
“类型”:“通知读取”,
“用户名”:用户名,
“通知id”:通知id,
}
send(JSON.stringify(data));
$(“通知容器”).fadeToggle(300);
$(“通知id”)。淡出(“缓慢”);
返回false;
});
//websocket脚本-客户端*
var loc=窗口位置
var formData=$(“#形式”)
var msgInput=$(“#id#u消息”)
var chatHolder=$(“#聊天项目”)
var me=$('#myUsername').val()
风险值通知=$(“#通知链接”)
var wsStart='ws://'
如果(loc.protocol==“https:”){
wsStart='wss://'
}
var endpoint=wsStart+loc.host+loc.pathname
var套接字=新的重新连接WebSocket(端点)
//下面是我收到的消息
socket.onmessage=函数(e){
var data=JSON.parse(event.data);
//找到通知图标/按钮/任何东西并显示一个红点,将通知id作为id或数据属性添加到元素中。
notification.append(“+notification.notification\u id)
控制台日志(“消息”,e)
var chatDataMsg=JSON.parse(e.data)
chatHolder.append(“
  • ”+chatDataMsg.message+”来自“+chatDataMsg.username+”
  • ”) } //下面是我要传达的信息 socket.onopen=函数(e){ 控制台日志(“打开”,e) formData.submit(函数(事件){ event.preventDefault() var msgText=msgInput.val() var finalData={ “消息”:msgText } socket.send(JSON.stringify(finalData)) formData[0]。重置() }) }
    导航栏

    <li id="notification_li" class="nav-item">
      <a class="nav-link" href="#" id="notificationLink">
        <i class="fas fa-envelope"></i>&nbsp; Inbox</a>
      {% for notifications in notification %}
      <span id="notification_id{{notification_id}}">{{ notifications.notification_chat }}</span>
      {% endfor %}
      <div id="notificationContainer">
        <div id="notificationTitle">Notifications</div>
        <div id="notificationsBody" class="notifications">
          {% for notifications in notification %}
          <a href="{% url 'chat:thread' user %}">
            <span id="notification-{{notification.id}}">
              {{ notifications.notification_chat.message }}
              via {{ notifications.notification_chat.user }}
              at {{ notifications.notification_chat.thread.timestamp }}
            </span>
          </a>
    ...
    
  • {%用于通知%中的通知} {{notifications.notification_chat}} {%endfor%} 通知 {%用于通知%中的通知} ...
  • 问题应该来自您的模型文件。
    非空
    约束是在一个字段上设置的,当您试图将其创建为空时,该字段会引发错误。因此,要解决这个问题,您需要设置
    空=真
    。 例如:

    date_of_birth = models.DateField(blank=True, null=True)
    

    尝试查看
    create\u chat\u message
    函数中使用的模型。

    问题应该来自模型文件。
    NOT NULL
    约束设置在一个字段上,该字段在您尝试将其创建为空时会引发错误。因此,为了克服此问题,您需要设置
    NULL=True
    。 例如:

    date_of_birth = models.DateField(blank=True, null=True)
    

    尝试查看
    create\u chat\u message
    功能中使用的型号。

    当您发送通知时,您不需要所有的rest代码,因此您可以简单地添加
    return

    if message_type == "notification_read":
        # Update the notification read status flag in Notification model.
        notification = Notification.object.get(id=notification_id)
        notification.notification_read = True
        notification.save()  #commit to DB
        print("notification read")
        return
    如果消息类型==“通知读取”:
    #更新通知模型中的通知读取状态标志。
    notification=notification.object.get(id=notification\u id)
    notification.notification\u read=True
    通知。保存()#提交到数据库
    打印(“通知已读”)
    
    return
    当您发送的通知被读取时,您不需要所有的rest代码,因此您可以简单地添加
    return

    if message_type == "notification_read":
        # Update the notification read status flag in Notification model.
        notification = Notification.object.get(id=notification_id)
        notification.notification_read = True
        notification.save()  #commit to DB
        print("notification read")
        return
    如果消息类型==“通知读取”:
    #更新通知模型中的通知读取状态标志。
    notification=notification.object.get(id=notification\u id)
    notification.notification\u read=True
    通知。保存()#提交到数据库
    打印(“通知已读”)
    
    return
    @BearBrown你好,有什么想法吗?你好,我现在正在读,你还需要帮助吗?看起来
    @
    只有在我添加一些评论时才有效,否则我不会收到任何通知。
    创建聊天信息
    里面有什么代码?嗨@BearBrown
    创建聊天信息
    里面的代码在上面我不知道在问题中看到它,我认为问题可能就在它里面。@BearBrown嗨,有什么想法吗?嗨,我现在正在读,你还需要帮助吗?而且看起来
    @
    只有在我添加一些注释时才起作用,否则我不会收到任何通知。
    创建聊天信息
    里面有什么代码?嗨@BearBrown代码在里面e
    create\u chat\u message
    在上面,我在问题中没有看到它,我认为问题可能就在它里面。嗨,我不想在消息上设置
    null=True
    ,因为这样它将允许发送空白消息,我不想这样做?好的,所以你想阻止它发送空白消息。是的,我正在试图找出原因hy,因为当我硬刷新页面时,
    websocket.receive
    不会发送任何空白消息。但是,我发送的消息越多,空白消息就越多。嗨,我不想在消息上设置
    null=True
    ,因为这样它将允许发送空白消息,我不想这样做?好的,那么你想继续吗阻止它发送空白消息。是