Ever input in chatwindow is considered a new Django Session

I wish for a user to interact with a chat window and to receive responses from backed(as a bot), all of which is recorded under a session, But a new session seems to be created every time instead of the current one persisting.

I have tried a lot of things, even creating a bare bones version of the project just to attempt session management but I have consistently failed.

At the beggining I assumed it had to do with my models i created, I created my own session object with a one to many relationship where one session may have many chatMessages

class Session(models.Model): 
    session_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable = False)
    start_time = models.DateTimeField(default=timezone.now)
    end_time = models.DateTimeField(null=True, blank=True) # inititalized empty originally
    session_length = models.DurationField(null= True, blank=True)

#each message by bot and user is recorded in the chatmessages model linked to an instance of their unique session
# that was created
class chatMessages(models.Model):
    session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='messages')
    role = models.CharField(max_length=50)
    content= models.TextField()
    timestamp = models.DateTimeField(default=timezone.now)

I later on decided to change the session_id to match the Django made middle ware one, wondering if the discrepancy between the two was causing an issue.

In my view this is how I called it

def chat(request):
    try:
        # Ensure a Django session exists
        if not request.session.session_key:
            request.session.save()

        session_id = request.session.session_key
        session, created = Session.objects.get_or_create(
            session_id=session_id,
            defaults={'start_time': timezone.now()}
        )

This would just check if a Django sessionid exists, if it does exist it simply gets that existing session.

My temporary “frontend” I believe was behaving correctly too

function displayMessage(message, isUser) {
            const chatWindow = document.getElementById('chat-window');
            const messageBubble = document.createElement('div');
            messageBubble.className = isUser ? 'bubble user' : 'bubble response';
            messageBubble.textContent = message;
            chatWindow.appendChild(messageBubble);
            chatWindow.scrollTop = chatWindow.scrollHeight;
        }

        // Function to load chat history
        async function loadChatHistory() {
            const chatWindow = document.getElementById('chat-window');
            chatWindow.innerHTML = ''; // Clear existing messages

            try {
                const response = await fetch('http://127.0.0.1:8000/chat/', {
                    method: 'GET',
                    headers: {
                        'X-CSRFToken': getCookie('csrftoken'),
                    },
                    credentials: 'include'
                });

                if (response.ok) {
                    const data = await response.json();
                    data.chat_history.forEach(message => {
                        displayMessage(message.content, message.role === 'user');
                    });
                } else {
                    console.error('Error loading chat history:', response.statusText);
                }
            } catch (error) {
                console.error('Error loading chat history:', error);
            }
        }

So again, summarizing my issue. I wish to have a chatwindow where a user sends an input, that input is appended as a bubble to the window, that input is sent to the backend and the backend sends a response that is also appended to the window. Simple enough, the hard part is is that I wish to manage these sessions and record them, my attempts at adding session management always make it so the bubbles disappear(only when session management is in place) and every input is considered a single session. A new session is being created with every message.

I have tried changing my Session model session_id from a uuid one to simply use the django one that’s provided. I have tried Going without a sessionid, passing sessionid as a header into the backend, recreating the project from scratch to attempt a miniature version of session management. Youtube videos, AI, you name it.

I am at a loss as to what to do. I would greatly appreciate not only assistance but if anyone has code or could replicate a simple chat window with response from user and predetermined messages from backend with proper session management, I would love to take a look at it and try and reverse engineer it.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật