To get this project started let me first go over how all is set up. This post will be broken down in two sections. The first halfwill be my chat app without real time and the second half will include django channels so you see things in real time.
Two people will be able to be logged in a chat room at one time. As one person sends a message the other will receive the message without needing to update.
To test the code login and create some users. Add both users into the url ad a thread will be linked or created.
Our app Without Channels
What out app looks like so far:
Now lets add real time features to our app
- Add Channels to our project (settings.py)
- Template (Socket Connection)
- Redis Server
- Send form data to consumer
1 – Add Channels to our project
This will temporary break our project until we build routing.py
2 – routing.py
Now we will need to build a base routing.py file
3 – Consumer
Now its time to build a base consumer. We will test this when we connect to our template.
Here is our consumer. It doesent do anything but print out a few things in our command prompt so we can see if its properly working.
Import and add your consumer as a path in routing.py. We will want our socket path to be the same as our path in urls.py.
4 – Template (Socket Connection)
Lets connect our template to our consumer and see if its working.
In our template we added the following script tags and code
5 – Redis Server
Now be sure your redis server is on for testing.
When we open up our site we should see the following in the command prompt and console
Sending form data to consumer
Our form data currently gets sent to our consumer via ajax and gets handled by our view. We will remove this from our view and send our data to our consumer instead.
The piece our app will be able to write a message wich will save to the database and display on both users screens. I will come back to clean this article up later but for now will just post screen shots of the template and consumer & view.py.