无法让删除按钮在我的 Djangochat 聊天室应用程序中工作

Cannot get the delete button to work in my Djangochat room app

提问人:James Romero 提问时间:11/17/2023 最后编辑:Chukwujiobi CanonJames Romero 更新时间:11/19/2023 访问量:28

问:

单击删除按钮时,我在控制台和屏幕中收到以下消息:

未找到: /delete_message/125/ HTTP 删除 /delete_message/125/ 404 [0.05, 127.0.0.1:63513]。

相同的代码在另一个系统中有效,但在这里不行。该信息在数据库中具有正确的 ID。我希望用户能够删除可能包含错误信息或错误代码的消息。以下是提交代码:

房间.html

{% extends "base.html" %}

{% block title %} {{room.name}} | {% endblock title %}

{% block content %}

 <div class="p-5 text-center">

    <h3 class="lg:text-6xl text-white">Room: {{ room.name }}</h3>
 </div>

 <div class=" flex flex-wrap w-full ">
  

    <div class="w-full md:w-2/3 lg:mx-auto p-4 bg-white rounded-xl">

        <div class="chat-messages space-y-3" id="chat-messages">
            {% for message in messages %}
            <div id="message-{{message.id}" class="p-4 bg-gray-200 rounded-xl">

                <p class="font-bold"> {{message.user.username}} {{message.date_added}} </p> 
                <p> {{ message.content|safe }} </p> 
                <p>{% if message.user.username == current_user %}</p>
                 <form action="" method="post">
                                    {% csrf_token %}
                                    {{ form.as_p }}
                                     <button class="float-right d-inline" onclick="deleteMessage({{ message.id }})"> del
                                
                                </button>
                    <br/>
                    <br/>
                
            </div>
            {% endif %}
            {% endfor %}
            

        </div>

    </div> 
    
    <div class="w-full md:w-1/3 lg:mx-auto p-4 bg-white rounded xl">

        <form class="">

            <div>
                <textarea name="content" id="editor"></textarea>

            </div>

          

            <button  class="px-5 py-3 rounded-xl text-white bg-teal-600 hover: bg-teal-700" id="chat-message-submit">
                Submit
            </button>
        </form>

    </div>

    
 </div>


{% endblock content %}



{% block scripts %}

{{ room.slug|json_script:"json-roomname" }}
{{ request.user.username|json_script:"json-username"}}


<script>
        $('#editor').on('keydown', function(event) {
            if (!event.shiftKey && event.which == '13') {
                $('#chat-message-submit').click();
                return false;
            }
        });
</script>


<script>
    function deleteMessage(messageId) {
        const request = new XMLHttpRequest();
        request.open('DELETE', `/delete_message/${messageId}/`);
        request.setRequestHeader("X-CSRFToken", document.querySelector('[name=csrfmiddlewaretoken]').value);
        request.send();
        
        request.onload = function() {
            if (request.status === 200) {
                // The message was deleted.
                // Remove the message from the DOM.
                const messageElement = document.querySelector(`#message-${messageId}`);
                messageElement.parentNode.removeChild(messageElement);
            } else if (request.status === 403) {
                // The user is not allowed to delete the message.
                // Display an error message or handle it as needed.
                alert('You are not allowed to delete this message.');
            } else if (request.status === 404) {
                // The message was not found.
                // Display an error message or handle it as needed.
                alert('The message was not found.');
            } else {
                // Something went wrong deleting the message.
                // Display an error message or handle it as needed.
                alert('Error in deleting the message.');
            }
        };
    }
    </script>

<script>
    $('#chat-message-input').focus();
    const roomName = JSON.parse(document.getElementById('json-roomname').textContent);
    const userName = JSON.parse(document.getElementById('json-username').textContent);

    const chatSocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/'
        + roomName
        + '/'
    );

    chatSocket.onmessage = function(e) {
        console.log('A message was sent by' + userName)

        const data = JSON.parse(e.data);
        var timestamp = createTimestamp(new Date())

        if(data.message){
            let html = "<div>";
                html += "<h5 class='badge badge-success d-inline'>" + data.username + "</h5>";
                html += "<small class='d-inline' style='font-style: 11px;'>" + timestamp + "</small>";
                html += "</div>";
                html += "<div>";
                html += "<div style='white-space: pre-wrap;'>" + data.message +"</div>";
                html += "</div>";
            
            var newElement = document.createElement('div');
            newElement.innerHTML = html;
            document.querySelector('#chat-messages').appendChild(newElement); 

                scrollToBottom();
        }
    }

    chatSocket.onclose = function(e) {
        console.log('The WebSocket was closed! The server is probably restarting, please wait!')
    }

    document.querySelector('#chat-message-submit').onclick = function(e) {
        e.preventDefault();
   

        const messageInputDom = document.querySelector('#editor');
        const editorContent = CKEDITOR.instances.editor.getData();
        messageInputDom.value = editorContent;
        
        
        const message = messageInputDom.value;
        const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]');

        chatSocket.send(JSON.stringify({
            'message': message,
            'username': userName,
            'room': roomName,
            'csrfmiddlewaretoken': csrftoken
        }));

        messageInputDom.value = '';
        CKEDITOR.instances.editor.setData('');
        
        location.reload();

        return false;
    }

    function createTimestamp(date) {
        return date.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric'});
    }

    function scrollToBottom() {
        const objDiv = document.querySelector('#chat-messages');
        objDiv.scrollTop = objDiv.scrollHeight;
    }

    scrollToBottom();
</script>


<script>
 
    CKEDITOR.replace( 'editor' );
    height: '60px'
    ;
    
    CKEDITOR.config.allowedContent = true;
    CKEDITOR.config.removeFormatAttributes = '';
    CKEDITOR.config.toolbarGroups = [
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
        { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
        { name: 'forms', groups: [ 'forms' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
        { name: 'links', groups: [ 'links' ] },
        { name: 'insert', groups: [ 'insert' ] },
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'colors', groups: [ 'colors' ] },
        { name: 'tools', groups: [ 'tools' ] },
        { name: 'others', groups: [ 'others' ] },
        { name: 'about', groups: [ 'about' ] }
    ];
    CKEDITOR.config.extraPlugins ='codesnippet, markdown' ;
   
    CKEDITOR.format_tags = 'p;h1;h2;h3;pre';
    CKEDITOR.config.removeButtons = 'Cut,SelectAll,Find,Save,NewPage,ExportPdf,Preview,Print,Templates,PasteText,Paste,PasteFromWord,Form,HiddenField,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,Image,Table,HorizontalRule,About,Maximize,TextColor,Language,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock,CreateDiv,Blockquote,Outdent,Indent,BulletedList,NumberedList,CopyFormatting,RemoveFormat';
    CKEDITOR.config.removePlugins = 'scayt,exportpdf,contextmenu,liststyle,tabletools,tableselection'
    CKEDITOR.config.codeSnippet_languages = {
        python: 'Py',
        javascript: 'JS',
        css: 'CSS',
        html: 'HTML',
        sql: 'SQL',
        json: 'JSON',
        http: 'HTTP',
        xml: 'XML',
        markdown: 'MD',
        vbscript: 'VB'
    };
 
</script>




{% endblock scripts %}

我已经重写了代码,复制并粘贴了代码,在另一个程序中尝试了代码(仍然有效),但另一个程序没有做这个程序正在做的事情。

JavaScript Django

评论


答: 暂无答案