Getting errors while trying to integrate django-private-chat in my application?

假如想象 提交于 2020-01-30 10:56:49

问题


I am working on an application where I want to implement the django-private-chat in for one to one messaging feature after I did everything which is said in the documentation I ran the server and got to the link http://127.0.0.1:8000/dialogs/ I am getting the blank page and when I see in console I am seeing this javascript error please help me out I have included the error traceback also

My dialogs.html:

{% extends "django_private_chat/base.html" %} 
{% load static %}
{% load i18n %}
{% block css %}
        <link href="{% static "django_private_chat/css/django_private_chat.css" %}" rel="stylesheet" type="text/css" media="all">

    {% endblock css %}


    {% block content %}
        <input id="owner_username" type="hidden" value="{{ request.user.username }}">
        <div class="container">
            <div class="col-md-3">
                <div class="user-list-div">
                    <ul>
                        {% for dialog in object_list %}
                            <li>
                                {% if dialog.owner == request.user %}
                                    {% with dialog.opponent.username as username %}
                                        <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}"
                                           class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a>
                                    {% endwith %}
                                {% else %}
                                    {% with dialog.owner.username as username %}
                                        <a href="{% url 'dialogs_detail' username %}" id="user-{{ username }}"
                                           class="btn btn-danger">{% trans "Chat with" %} {{ username }}</a>
                                    {% endwith %}
                                {% endif %}
                            </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
            <div class="col-md-9">
                <div class="row">
                    <div class="col-md-3 col-md-offset-9">
                        <span class="pull-right" hidden id="typing-text">
                            <strong>{{ opponent_username }} {% trans "is typing..." %}</strong>
                        </span>
                    </div>
                    <p>
                        {{ opponent_username }}
                    </p>
                    <p class="text-success" id="online-status" style="display: none">{% trans "Online" %}</p>
                    <p class="text-danger" id="offline-status" style="display: none">{% trans "Offline" %}</p>

                    <div class="messages-container">
                        <div id="messages" class="messages">
                            {% for msg in active_dialog.messages.all %}
                                <div class="row {% if msg.read %}msg-read{% else %}msg-unread{% endif %}"
                                     data-id="{{ msg.id }}">
                                    <p class="{% if msg.sender == request.user %}pull-left{% else %}pull-right{% endif %}">
                                        <span class="username">{{ msg.sender.username }}:</span>
                                        {{ msg.text }}
                                        <span class="timestamp">&ndash; <span
                                                data-livestamp="{{ msg.get_formatted_create_datetime }}">{{ msg.get_formatted_create_datetime }}</span></span>
                                    </p>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="add-message">
                        <div class="form-group">
                            <textarea id="chat-message" class="form-control message"
                                      placeholder="{% trans 'Write a message' %}"></textarea>
                        </div>

                        <div class="form-group clearfix">
                            <input id="btn-send-message" type="submit" class="btn btn-primary pull-right send-message"
                                   style="margin-left: 10px;" value="{% trans 'Send' %}"/>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    {% endblock %}

    {% block extra_js %}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/scrollmonitor/1.2.0/scrollMonitor.js"
                integrity="sha256-BseZlDlA+yL4qu+Voi82iFa5aaifralQEXIjOjaXgeo=" crossorigin="anonymous"></script>
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

        <script>
            var base_ws_server_path = "{{ ws_server_path }}";
            $(document).ready(function () {
                var websocket = null;
                var monitor = null;
                var scrollHeight = 10;

                function initReadMessageHandler(containerMonitor, elem) {
                    var id = $(elem).data('id');
                    var elementWatcher = containerMonitor.create(elem);
                    elementWatcher.enterViewport(function () {
                        var opponent_username = getOpponnentUsername();
                        var packet = JSON.stringify({
                            type: 'read_message',
                            session_key: '{{ request.session.session_key }}',
                            username: opponent_username,
                            message_id: id
                        });
                        $(elem).removeClass('msg-unread').addClass('msg-read');
                        websocket.send(packet);
                    });
                }

                function initScrollMonitor() {
                    var containerElement = $("#messages");
                    var containerMonitor = scrollMonitor.createContainer(containerElement);
                    $('.msg-unread').each(function (i, elem) {
                        if ($(elem).hasClass('opponent')){
                            initReadMessageHandler(containerMonitor, elem);
                        }

                    });
                    return containerMonitor
                }

                function getOpponnentUsername() {
                    return "{{ opponent_username }}";
                }

                // TODO: Use for adding new dialog
                function addNewUser(packet) {
                    $('#user-list').html('');
                    packet.value.forEach(function (userInfo) {
                        if (userInfo.username == getUsername()) return;
                        var tmpl = Handlebars.compile($('#user-list-item-template').html());
                        $('#user-list').append(tmpl(userInfo))
                    });
                }

                function addNewMessage(packet) {
                    var msg_class = "";
                    if (packet['sender_name'] == $("#owner_username").val()) {
                        msg_class = "pull-left";
                    } else {
                        msg_class = "pull-right";
                    }
                    var msgElem =
                        $('<div class="row msg-unread" data-id="' + packet.message_id + '">' +
                            '<p class="' + msg_class + '">' +
                            '<span class="username">' + packet['sender_name'] + ': </span>' +
                            packet['message'] +
                            ' <span class="timestamp">&ndash; <span data-livestamp="' + packet['created'] + '"> ' + packet['created'] + '</span></span> ' +
                            '</p> ' +
                            '</div>');
                    $('#messages').append(msgElem);
                    scrollToLastMessage()
                }

                function scrollToLastMessage() {
                    var $msgs = $('#messages');
                    $msgs.animate({"scrollTop": $msgs.prop('scrollHeight')})
                }

                function generateMessage(context) {
                    var tmpl = Handlebars.compile($('#chat-message-template').html());
                    return tmpl({msg: context})
                }

                function setUserOnlineOffline(username, online) {
                    var elem = $("#user-" + username);
                    if (online) {
                        elem.attr("class", "btn btn-success");
                    } else {
                        elem.attr("class", "btn btn-danger");
                    }
                }

                function gone_online() {
                    $("#offline-status").hide();
                    $("#online-status").show();
                }

                function gone_offline() {
                    $("#online-status").hide();
                    $("#offline-status").show();
                }

                function flash_user_button(username) {
                    var btn = $("#user-" + username);
                    btn.fadeTo(700, 0.1, function () {
                        $(this).fadeTo(800, 1.0);
                    });
                }

                function setupChatWebSocket() {
                    var opponent_username = getOpponnentUsername();
                    websocket = new WebSocket(base_ws_server_path + '{{ request.session.session_key }}/' + opponent_username);

                    websocket.onopen = function (event) {
                        var opponent_username = getOpponnentUsername();

                        var onOnlineCheckPacket = JSON.stringify({
                            type: "check-online",
                            session_key: '{{ request.session.session_key }}',
                            username: opponent_username
                            {#                      Sending username because the user needs to know if his opponent is online #}
                        });
                        var onConnectPacket = JSON.stringify({
                            type: "online",
                            session_key: '{{ request.session.session_key }}'

                        });

                        console.log('connected, sending:', onConnectPacket);
                        websocket.send(onConnectPacket);
                        console.log('checking online opponents with:', onOnlineCheckPacket);
                        websocket.send(onOnlineCheckPacket);
                        monitor = initScrollMonitor();
                    };


                    window.onbeforeunload = function () {

                        var onClosePacket = JSON.stringify({
                            type: "offline",
                            session_key: '{{ request.session.session_key }}',
                            username: opponent_username,
                            {# Sending username because to let opponnent know that the user went offline #}
                        });
                        console.log('unloading, sending:', onClosePacket);
                        websocket.send(onClosePacket);
                        websocket.close();
                    };


                    websocket.onmessage = function (event) {
                        var packet;

                        try {
                            packet = JSON.parse(event.data);
                            console.log(packet)
                        } catch (e) {
                            console.log(e);
                        }

                        switch (packet.type) {
                            case "new-dialog":
                                // TODO: add new dialog to dialog_list
                                break;
                            case "user-not-found":
                                // TODO: dispay some kind of an error that the user is not found
                                break;
                            case "gone-online":
                                if (packet.usernames.indexOf(opponent_username) != -1) {
                                    gone_online();
                                } else {
                                    gone_offline();
                                }
                                for (var i = 0; i < packet.usernames.length; ++i) {
                                    setUserOnlineOffline(packet.usernames[i], true);
                                }
                                break;
                            case "gone-offline":
                                if (packet.username == opponent_username) {
                                    gone_offline();
                                }
                                setUserOnlineOffline(packet.username, false);
                                break;
                            case "new-message":
                                if (packet['sender_name'] == opponent_username || packet['sender_name'] == $("#owner_username").val()) {
                                    addNewMessage(packet);
                                    if (packet['sender_name'] == opponent_username) {
                                        initReadMessageHandler(monitor, $("div[data-id='" + packet['message_id'] + "']"));
                                    }
                                } else {
                                    flash_user_button(packet['sender_name']);
                                }
                                break;
                            case "opponent-typing":
                                var typing_elem = $('#typing-text');
                                if (!typing_elem.is(":visible")) {
                                    typing_elem.fadeIn(500);
                                } else {
                                    typing_elem.stop(true);
                                    typing_elem.fadeIn(0);
                                }
                                typing_elem.fadeOut(3000);
                                break;
                            case "opponent-read-message":
                                if (packet['username'] == opponent_username) {
                                    $("div[data-id='" + packet['message_id'] + "']").removeClass('msg-unread').addClass('msg-read');
                                }
                                break;

                            default:
                                console.log('error: ', event)
                        }
                    }
                }

                function sendMessage(message) {
                    var opponent_username = getOpponnentUsername();
                    var newMessagePacket = JSON.stringify({
                        type: 'new-message',
                        session_key: '{{ request.session.session_key }}',
                        username: opponent_username,
                        message: message
                    });
                    websocket.send(newMessagePacket)
                }

                $('#chat-message').keypress(function (e) {
                    if (e.which == 13 && this.value) {
                        sendMessage(this.value);
                        this.value = "";
                        return false
                    } else {
                        var opponent_username = getOpponnentUsername();
                        var packet = JSON.stringify({
                            type: 'is-typing',
                            session_key: '{{ request.session.session_key }}',
                            username: opponent_username,
                            typing: true
                        });
                        websocket.send(packet);
                    }
                });

                $('#btn-send-message').click(function (e) {
                    var $chatInput = $('#chat-message');
                    var msg = $chatInput.val();
                    if (!msg) return;
                    sendMessage($chatInput.val());
                    $chatInput.val('')
                });

                setupChatWebSocket();
                scrollToLastMessage();
            });

        </script>
    {% endblock %}

My base.html:

{% load static %}

<!-- Their site uses old school block layout -->
{% block extra_js %}

    <!-- Your package using 2SoD block layout -->
    {% block javascript %}

        <script src="{% static 'js/ninja.js' %}" type="text/javascript"></script>


    {% endblock javascript %}

{% endblock extra_js %}

actually did the steps that are said in django-private-chat documentation and I even didnt changed anything in the code please help me out I think this is the javascript error in django application anyone please help me

来源:https://stackoverflow.com/questions/59925329/getting-errors-while-trying-to-integrate-django-private-chat-in-my-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!