Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
Cannot connect JS Event Source to Python (Django) backend server

I'm working with Django Framework + Javascript and want to create a server-sent event which gonna send messages to the front-end.

Here is my Js-client part:

btn.addEventListener('click', function(event){
console.log('started...');

var url = new URL('http://127.0.0.1:8000/get/stream/data/');
var source = new EventSource(url);

source.onopen = function(){
console.log('Source has been connected....');
};

console.log(source);
source.onmessage = function(event){
data = JSON.parse(event.data);

console.log('on message event', event, data);
console.log(event);

};

source.onerror = function(err) {
source.close();
console.error("EventSource failed:", err);
};

source.onclose = function(){
evtSource.close();
console.log('event source has been closed');
}
});

Python-Django part:

def prepare_stream_data():
import json
from django.core.serializers.json import DjangoJSONEncoder
while True:

    for i in range(30):
        yield json.dumps('%s' % i, cls=DjangoJSONEncoder)
        print(i)
        time.sleep(5)

def send_stream_data(request):
    stream_data = prepare_stream_data()

    response = django.http.StreamingHttpResponse(stream_data,
    content_type='text/event-stream')

    return response

urls.py

path('get/stream/data/', main_course_api.send_stream_data, name='stream_data')

Django basically works and I see the result in console...., when I click on the button, but it shows me in JS console, that event source is not connected (readyState equals to 0) and does not receive any messages) :(

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!