# Realtime frontend data view

**URL:** <https://forum.djangoproject.com/t/realtime-frontend-data-view/23948>\
**Category:** Async/Channels\
**Created:** [September 18, 2023, 11:36am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948 "2023-09-18T11:36:07Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![suchira84](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/suchira84/32/15990_2.png) [@suchira84](https://forum.djangoproject.com/u/suchira84)\
**Post date:** [September 18, 2023, 11:36am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948/1 "2023-09-18T11:36:07Z")

</div>

I just want to create a project to view the real-time output from the ‘templates/index.html’ without refreshing the page. Additionally, there is no need to insert data into the database using the template, as I use Django admin to insert data manually. Web Socket connects perfectly.

I just want to create a project to view the real-time output from the ‘templates/index.html’ without refreshing the page. Additionally, there is no need to insert data into the database using the template, as I use Django admin to insert data manually. Web Socket connects perfectly.

# views.py

from django.shortcuts import render  
from .models import MyModel

## def index(request): people = MyModel.objects.all() return render(request, ‘index.html’, {‘people’: people})

# realapp/urls.py

from django.urls import path  
from . import views

## urlpatterns = [path(‘’, views.index, name=‘index.html’),]

# realtime/urls.py

from django.contrib import admin  
from django.urls import path, include

## urlpatterns = [path(‘admin/’, admin.site.urls), path(‘’, include(‘realapp.urls’)),]

My Realtime App

Realtime App My Realtime App  
var socket = new WebSocket(‘ws://127.0.0.1:9000/ws/real/’);

```
    socket.onmessage = function(event) {
        var data = JSON.parse(event.data);
        var message = data.message;
        document.getElementById('realtime-data').innerHTML = message;
    };

    
    socket.onopen = function(event) {
        socket.send(JSON.stringify({
            'message': 'Hello, server!'
        }));
    };
</script>

```

# realapp/models.py

from django.db import models

class MyModel(models.Model):  
name = models.CharField(max\_length=100)  
desc = models.CharField(max\_length=200)

# realapp/admin.py

## from django.contrib import admin from .models import MyModel

# admin.site.register(MyModel)

realtime/asgi.py

* * *

#settings.py  
import os  
from django.core.asgi import get\_asgi\_application  
from channels.routing import ProtocolTypeRouter, URLRouter  
from channels.auth import AuthMiddlewareStack  
from realapp.routing import websocket\_urlpatterns # Import your WebSocket URL patterns

os.environ.setdefault(‘DJANGO\_SETTINGS\_MODULE’, ‘realtime.settings’)

## application = ProtocolTypeRouter({ “http”: get\_asgi\_application(), “websocket”: AuthMiddlewareStack( URLRouter( websocket\_urlpatterns ) ), })

# realapp/consumers.py

import json  
from channels.generic.websocket import AsyncWebsocketConsumer  
from asgiref.sync import async\_to\_sync

class RealtimeConsumer(AsyncWebsocketConsumer):  
async def connect(self):  
await self.channel\_layer.group\_add(‘realtime\_group’, self.channel\_name)  
await self.accept()

async def disconnect(self, close\_code):  
await self.channel\_layer.group\_discard(‘realtime\_group’, self.channel\_name)

async def receive(self, text\_data):  
data = json.loads(text\_data)

```
message = data['message']

await self.channel_layer.group_send(
    'realtime_group',
    {
        'type': 'realtime_message',
        'message': message
    }
)

```

async def realtime\_message(self, event):  
message = event[‘message’]

```
await self.send(text_data=json.dumps({
    'message': message
}))

```

* * *

# realapp/routing.py

from django.urls import re\_path  
from . import consumers

websocket\_urlpatterns = [  
re\_path(r’ws/real/$', consumers.RealtimeConsumer.as\_asgi()),  
]

* * *

# settings.py

from pathlib import Path  
import os

BASE\_DIR = Path(file).resolve().parent.parent

SECRET\_KEY = ‘django-insecure-6d5f@scw%v-kmse5w8hdmo9fyxka07)$mu)24&t\*x7&\_v(ln8v’

DEBUG = True

ALLOWED\_HOSTS =

INSTALLED\_APPS = [  
‘channels’,  
‘realapp’,  
‘django.contrib.admin’,  
‘django.contrib.auth’,  
‘django.contrib.contenttypes’,  
‘django.contrib.sessions’,  
‘django.contrib.messages’,  
‘django.contrib.staticfiles’,  
]

MIDDLEWARE = [  
‘django.middleware.security.SecurityMiddleware’,  
‘django.contrib.sessions.middleware.SessionMiddleware’,  
‘django.middleware.common.CommonMiddleware’,  
‘django.middleware.csrf.CsrfViewMiddleware’,  
‘django.contrib.auth.middleware.AuthenticationMiddleware’,  
‘django.contrib.messages.middleware.MessageMiddleware’,  
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,  
]

ROOT\_URLCONF = ‘realtime.urls’

TEMPLATES = [  
{  
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,  
‘DIRS’: ,  
‘APP\_DIRS’: True,  
‘OPTIONS’: {  
‘context\_processors’: [  
‘django.template.context\_processors.debug’,  
‘django.template.context\_processors.request’,  
‘django.contrib.auth.context\_processors.auth’,  
‘django.contrib.messages.context\_processors.messages’,  
],  
},  
},  
]

ASGI\_APPLICATION = ‘realtime.routing.application’

CHANNEL\_LAYERS = {  
‘default’: {  
‘BACKEND’: ‘channels.layers.InMemoryChannelLayer’, # Use InMemoryChannelLayer for development  
},  
}

DATABASES = {  
‘default’: {  
‘ENGINE’: ‘django.db.backends.sqlite3’,  
‘NAME’: BASE\_DIR / ‘db.sqlite3’,  
}  
}

AUTH\_PASSWORD\_VALIDATORS = [  
{  
‘NAME’: ‘django.contrib.auth.password\_validation.UserAttributeSimilarityValidator’,  
},  
{  
‘NAME’: ‘django.contrib.auth.password\_validation.MinimumLengthValidator’,  
},  
{  
‘NAME’: ‘django.contrib.auth.password\_validation.CommonPasswordValidator’,  
},  
{  
‘NAME’: ‘django.contrib.auth.password\_validation.NumericPasswordValidator’,  
},  
]

LANGUAGE\_CODE = ‘en-us’

TIME\_ZONE = ‘UTC’

USE\_I18N = True

USE\_TZ = True

STATIC\_URL = ‘/static/’  
STATIC\_ROOT = os.path.join(BASE\_DIR, ‘staticfiles’)

DEFAULT\_AUTO\_FIELD = ‘django.db.models.BigAutoField’

* * *

# Folder Structure

.  
├── db.sqlite3  
├── manage.py  
├── realapp  
│ ├── admin.py  
│ ├── apps.py  
│ ├── consumers.py  
│ ├── init.py  
│ ├── migrations  
│ │ ├── 0001\_initial.py  
│ │ ├── init.py  
│ │ └── pycache  
│ │ ├── 0001\_initial.cpython-310.pyc  
│ │ └── init.cpython-310.pyc  
│ ├── models.py  
│ ├── pycache  
│ │ ├── admin.cpython-310.pyc  
│ │ ├── apps.cpython-310.pyc  
│ │ ├── consumers.cpython-310.pyc  
│ │ ├── init.cpython-310.pyc  
│ │ ├── models.cpython-310.pyc  
│ │ ├── routing.cpython-310.pyc  
│ │ ├── urls.cpython-310.pyc  
│ │ └── views.cpython-310.pyc  
│ ├── routing.py  
│ ├── templates  
│ │ └── index.html  
│ ├── tests.py  
│ ├── urls.py  
│ └── views.py  
├── realtime  
│ ├── asgi.py  
│ ├── init.py  
│ ├── pycache  
│ │ ├── asgi.cpython-310.pyc  
│ │ ├── init.cpython-310.pyc  
│ │ ├── settings.cpython-310.pyc  
│ │ ├── urls.cpython-310.pyc  
│ │ └── wsgi.cpython-310.pyc  
│ ├── settings.py  
│ ├── urls.py  
│ └── wsgi.py  
└── staticfiles  
└── admin  
├── css  
│ ├── autocomplete.css  
│ ├── base.css  
│ ├── changelists.css  
│ ├── dark\_mode.css  
│ ├── dashboard.css  
│ ├── forms.css  
│ ├── login.css  
│ ├── nav\_sidebar.css  
│ ├── responsive.css  
│ ├── responsive\_rtl.css  
│ ├── rtl.css  
│ ├── vendor  
│ │ └── select2  
│ │ ├── LICENSE-SELECT2.md  
│ │ ├── select2.css  
│ │ └── select2.min.css  
│ └── widgets.css  
├── img  
│ ├── calendar-icons.svg  
│ ├── gis  
│ │ ├── move\_vertex\_off.svg  
│ │ └── move\_vertex\_on.svg  
│ ├── icon-addlink.svg  
│ ├── icon-alert.svg  
│ ├── icon-calendar.svg  
│ ├── icon-changelink.svg  
│ ├── icon-clock.svg  
│ ├── icon-deletelink.svg  
│ ├── icon-no.svg  
│ ├── icon-unknown-alt.svg  
│ ├── icon-unknown.svg  
│ ├── icon-viewlink.svg  
│ ├── icon-yes.svg  
│ ├── inline-delete.svg  
│ ├── LICENSE  
│ ├── README.txt  
│ ├── search.svg  
│ ├── selector-icons.svg  
│ ├── sorting-icons.svg  
│ ├── tooltag-add.svg  
│ └── tooltag-arrowright.svg  
└── js  
├── actions.js  
├── admin  
│ ├── DateTimeShortcuts.js  
│ └── RelatedObjectLookups.js  
├── autocomplete.js  
├── calendar.js  
├── cancel.js  
├── change\_form.js  
├── collapse.js  
├── core.js  
├── filters.js  
├── inlines.js  
├── jquery.init.js  
├── nav\_sidebar.js  
├── popup\_response.js  
├── prepopulate\_init.js  
├── prepopulate.js  
├── SelectBox.js  
├── SelectFilter2.js  
├── theme.js  
├── urlify.js  
└── vendor  
├── jquery  
│ ├── jquery.js  
│ ├── jquery.min.js  
│ └── LICENSE.txt  
├── select2  
│ ├── i18n  
│ │ ├── af.js  
│ │ ├── ar.js  
│ │ ├── az.js  
│ │ ├── bg.js  
│ │ ├── bn.js  
│ │ ├── bs.js  
│ │ ├── ca.js  
│ │ ├── cs.js  
│ │ ├── da.js  
│ │ ├── de.js  
│ │ ├── dsb.js  
│ │ ├── el.js  
│ │ ├── en.js  
│ │ ├── es.js  
│ │ ├── et.js  
│ │ ├── eu.js  
│ │ ├── fa.js  
│ │ ├── fi.js  
│ │ ├── fr.js  
│ │ ├── gl.js  
│ │ ├── he.js  
│ │ ├── hi.js  
│ │ ├── hr.js  
│ │ ├── hsb.js  
│ │ ├── hu.js  
│ │ ├── hy.js  
│ │ ├── id.js  
│ │ ├── is.js  
│ │ ├── it.js  
│ │ ├── ja.js  
│ │ ├── ka.js  
│ │ ├── km.js  
│ │ ├── ko.js  
│ │ ├── lt.js  
│ │ ├── lv.js  
│ │ ├── mk.js  
│ │ ├── ms.js  
│ │ ├── nb.js  
│ │ ├── ne.js  
│ │ ├── nl.js  
│ │ ├── pl.js  
│ │ ├── ps.js  
│ │ ├── pt-BR.js  
│ │ ├── pt.js  
│ │ ├── ro.js  
│ │ ├── ru.js  
│ │ ├── sk.js  
│ │ ├── sl.js  
│ │ ├── sq.js  
│ │ ├── sr-Cyrl.js  
│ │ ├── sr.js  
│ │ ├── sv.js  
│ │ ├── th.js  
│ │ ├── tk.js  
│ │ ├── tr.js  
│ │ ├── uk.js  
│ │ ├── vi.js  
│ │ ├── zh-CN.js  
│ │ └── zh-TW.js  
│ ├── LICENSE.md  
│ ├── select2.full.js  
│ └── select2.full.min.js  
└── xregexp  
├── LICENSE.txt  
├── xregexp.js  
└── xregexp.min.js

21 directories, 159 files

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 18, 2023, 11:58am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948/2 "2023-09-18T11:58:03Z")

</div>

By “real-time”, do you mean that the data on the page is to be refreshed periodically, or that you want the server to push the data?

If you just want the browser to pull new data on a periodic basis (like once every 5 seconds), you could use JavaScript in the browser to do that. (Or even a JavaScript library like HTMX)

If you want the server to push updated data to the browser, then you’re looking at using Channels _with_ some JavaScript in the browser. (And again, something like HTMX can help there, too.)

---

<div class="post-metadata">

**Author:** ![suchira84](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/suchira84/32/15990_2.png) [@suchira84](https://forum.djangoproject.com/u/suchira84)\
**Post date:** [September 19, 2023, 3:38am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948/3 "2023-09-19T03:38:12Z")

</div>

Thanks KenWhitesell,

I’m still a beginner, I have just implemented the system using channels and connected through a webscocket, the connection establishes well. As you replied I do want to send data from the server and client (browser) needs to pull data. Is there anyway to send the code, if it is convenient. This is just a fundamental project. There is no way to attach the project over here.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 19, 2023, 3:42am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948/4 "2023-09-19T03:42:48Z")

</div>

I’m not following what you’re asking for here. If you’re needing help with the code you’ve written, post the code you have questions about in the body of your message, between lines of three backtick - ` characters, along with a description of the problem you’re having with that code.

---

<div class="post-metadata">

**Author:** ![suchira84](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/suchira84/32/15990_2.png) [@suchira84](https://forum.djangoproject.com/u/suchira84)\
**Post date:** [September 19, 2023, 3:50am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948/5 "2023-09-19T03:50:55Z")

</div>

Thanks, I just edited the post with the relevant codes.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 19, 2023, 5:39am UTC](https://forum.djangoproject.com/t/realtime-frontend-data-view/23948/6 "2023-09-19T05:39:09Z")

</div>

First, you need to surround the code for each file between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code for a file, then another line of ```.

Second, you need to identify what parts of this you need help with. (You don’t need to post your entire project, just the area where you’re encountering problems. We’ll ask for any additional code that may be needed.)
