Python Django View Template Renderlamak Yerine Json Döndürüyor.

YILSUK11

Megapat
Katılım
26 Temmuz 2016
Mesajlar
879
Makaleler
1
Çözümler
3
Selamlar, daha önce django ile chatbot yaptım. Özetleyecek olursam tüm yapı bir chat sayfasından oluşuyor herhangi bir şey yazıp butona tıkladığınızda otomatik olarak 'Merhaba' cevabı mesaj kutucuğuna ekleniyor. Yeni bir proje oluşturdum ve yapıyı biraz daha büyütmek istedim. Başlangıç sayfası oluşturdum 'Chat' butonu ve bilgi al tag' ını ekledim. 'Chat' butonuna basınca chat sayfasına yönlendiriyor ama render olması gereken template yerine siyah bir ekranda döndürmüş olduğum Json ile karşılaşıyorum. Bir kaç gündür sorunun ne olduğunu anlamaya çalışıyorum ama tıkandım. Chat sayfası için kullanmış olduğum template ve kodlar birebir aynı. Sizce sorun ne olabilir ?


1743714341949.png


Python views.py:
Python:
from django.shortcuts import render
from django.http import JsonResponse

def chat_view(request):
    if request.method == 'POST':
        user_message = request.POST.get('message', '')
      
        
        if user_message.lower() == 'merhaba':
            bot_response = "Merhaba!"
        else:
            bot_response = "Sadece 'merhaba' yazarsanız size merhaba derim :)"
          
        return JsonResponse({'response': bot_response})
  
    return render(request, 'chat.html')


JavaScript:
<script>

        function sendMessage() {

            const message = document.getElementById('message').value;

            if (!message) return;

            

            const chatbox = document.getElementById('chatbox');

            chatbox.innerHTML += `<div class="user">Sen: ${message}</div>`;

            

            fetch('', {

                method: 'POST',

                headers: {

                    'Content-Type': 'application/x-www-form-urlencoded',

                    'X-CSRFToken': '{{ csrf_token }}'

                },

                body: `message=${encodeURIComponent(message)}`

            })

            .then(response => response.json())

            .then(data => {

                chatbox.innerHTML += `<div class="bot">Bot: ${data.response}</div>`;

                chatbox.scrollTop = chatbox.scrollHeight;

            });

            

            document.getElementById('message').value = '';

        }

        
        document.getElementById('message').addEventListener('keypress', function(e) {

            if (e.key === 'Enter') sendMessage();

        });

    </script>
 
Son düzenleme:
Ben olsam aşağıdaki gibi yapıp denerdim:
Python:
from django.shortcuts import render
from django.http import JsonResponse

def chat_view(request):
    if request.method == 'POST':
        user_message = request.POST.get('message', '')
      
        if user_message.lower() == 'merhaba':
            bot_response = "Merhaba!"
        else:
            bot_response = "Sadece 'merhaba' yazarsanız size merhaba derim :)"
          
        return JsonResponse({'response': bot_response})
  
    return render(request, 'chat.html')  # GET işlemi olduğunda HTML sayfasını döndür
 

Bu konuyu görüntüleyen kullanıcılar

Technopat Haberler

Geri
Yukarı