[Python] Django request returning null?

Discussão em 'Python' iniciado por Stack, Outubro 6, 2024.

  1. Stack

    Stack Membro Participativo

    I'm building a chatbot withing Django using chat GPT's API and I'm following this tutorial https://www.youtube.com/watch?v=qrZGfBBlXpk. Anyway I don't see any difference in my code yet I'm running into a peculiar problem when I request from my html mile during the message sending process it returns null from the ''chatbot''

    def chatbot(request):
    if request.method == 'POST':
    message = request.POST.get('message')
    response = message
    return JsonResponse({'message': message, 'response': response})
    return render(request, 'chatbot.html')


    whats even weirder is when I console log the message in the JS

    messageForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const message = messageInput.value.trim()
    console.log('Message:', message)


    It shows up in the log? but somewhere along the line it returns null? I noticed when I used the davinci model and the chat would respond but only with nonsense which to me implied it wasnt actually getting MY message it was getting null and returning nonsense

    this Is the rest of the JS

    const messageItem = document.createElement('li');
    messageItem.classList.add('message', 'sent');
    messageItem.innerHTML = `<div class="message-sender">
    <div class="message-sender"
    <b>You<b>
    </div>
    <div class="message-content">
    ${message}
    </div>
    </div>`;
    messageList.appendChild(messageItem);
    messageInput.value = '';

    const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;

    fetch('', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urleencoded',
    'X-CSRFToken': csrftoken
    },
    body: new URLSearchParams({
    'csrfmiddlewaretoken': csrftoken,
    'message': message
    })
    })

    .then(response => response.json())
    .then(data => {
    const response = data.response;
    const messageItem = document.createElement('li');
    messageItem.classList.add('message', 'recieved');
    messageItem.innerHTML = `
    <div class="message-text">
    <div class="message-sender"
    <b>AI Helper<b>
    </div>
    <div class="message-content">
    ${response}
    </div>
    </div>
    `;
    messageList.appendChild(messageItem);
    });
    });
    ```

    Continue reading...

Compartilhe esta Página