• Stars
    star
    117
  • Rank 300,690 (Top 6 %)
  • Language
    JavaScript
  • Created about 4 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Real-time chat server with Django

Getting Started Guide

For a guide on pushing a project like this to production check out this repo: https://github.com/mitchtabian/HOWTO-django-channels-daphne.

This document is a guide to creating a new django project that uses:

  1. windows
  2. python3.8.2
  3. pip
  4. django 2.2.15 (LTS)
  5. virtualenv
  6. Redis
  7. django channels 2
  8. Postgres

Install Python3.8.2

Bottom of page: https://www.python.org/downloads/release/python-382/

Installing pip

  1. https://pypi.org/project/pip/
  2. Open cmd prompt
  3. pip install pip

Setup virtualenv

  1. Navigate to where you want to keep your django projects. I use D://DjangoProjects/
  2. Create D://DjangoProjects/ChatServerPlayground folder or whatever you want to name the project.
  3. Create a virtual environment to run the project in.
    • Typically I call it "venv" but you can call it something else if you like. Doesn't matter. djangoproject_venv for example.
    • python -m venv venv or python -m venv djangoproject_venv if you like
  4. Open a cmd prompt in your project directly
  5. Navigate into venv folder
    • cd venv
  6. Activate the virtual environment
    • Windows: Scripts\activate
    • Linux: source bin/activate
    • Mac (I think): source bin/activate

Install Django and create Django project

  1. Install django
  2. Create the django project
    • django-admin startproject ChatServerPlayground
  3. Rename root directory (ChatServerPlayground) to src
    • I prefer to name my root directory src because inside the project is another folder named ChatServerPlayground or whatever you called your project
    • So now you should have the following folder structure:
      • D://DjangoProjects/ChatServerPlayground/venv/src/
        • Inside src you will have a folder name ChatServerPlayground and a manage.py file
  4. Keep track of the libraries you use
    • pip freeze > requirements.txt
  5. Run the server to make sure it's working
    • python manage.py runserver
  6. Visit http://127.0.0.1:8000/

Postgres Setup (Windows)

Postgres needs to run as a service on your machine. Since I'm using windows I will show you how to do this on windows. When we launch this website in production at the end of the course I'll show you how to setup postgres on Linux.

  1. Download postgres: https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
    • I am using x86-64 version 10 for windows
  2. run the .exe file and go through the installation
    1. remember the superuser password you use. This is very important.
    2. port 5432 is the standard
  3. After installation confirm the service is running by opening the "Services" window on windows.
    • If it's not running then start it
  4. Confirm you have access to database
    1. open cmd prompt
    2. write psql postgres postgres
      • means: "connect to the database named 'postgres' with the user 'postgres'". 'postgres' is the default root user name for the database.
  5. Some commands you'll find useful:
    1. List databases
      • \l
    2. Connect to a different database
      • \c codingwithmitch_chat
      • Keep in mind you will not have any other databases. We will create one in a second.
    3. List the tables in a database \dt
    4. create a new database for our project
      • CREATE DATABASE codingwithmitch_chat_dev;
    5. Create a new user that has permissions to use that database
      • CREATE USER django WITH PASSWORD 'password';
      • These credentials are important to remember because they are used in the django postgres configuration.
    6. List all users
      • /du
    7. Give the new user all privileges on new db
      • GRANT ALL PRIVILEGES ON DATABASE codingwithmitch_chat_dev TO django;
    8. Test
      1. disconnect from db
        • \q
      2. Connect to the db with user
        • psql codingwithmitch_chat_dev django

Django and Postgres Setup

  1. Install psycopg2
    • pip install psycopg2
  2. Add to requirements
    • pip freeze > requirements.txt
  3. Update settings.py with the following postgres configuration
    DB_NAME = "codingwithmitch_chat_dev"
    DB_USER = "django"
    DB_PASSWORD = "password"
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': DB_NAME,
            'USER': DB_USER,
            'PASSWORD': DB_PASSWORD,
            'HOST': 'localhost',
            'PORT': '5432',
        }
    }
    
  4. Delete the sqlite database in project root
  5. migrate to commit changes to database
    • python manage.py migrate
  6. create a superuser
    • python manage.py createsuperuser
  7. log into admin
    • python manage.py runserver
    • visit http://127.0.0.1:8000/admin
    • This confirms the database is working correctly.

Install Redis (Required for Django Channels)

Redis does not work "out of the box" on windows. There is a number of ways to get it working but by far the easiest is to use Menurai.

  1. Links:
    1. download: https://www.memurai.com/get-memurai
    2. docs: https://docs.memurai.com/en/installation.html
  2. Just download the executable and run it.
  3. Update settings with CHANNEL_LAYERS configuration
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                "hosts": [('127.0.0.1', 6379)],
            },
        },
    }
    

Django Channels setup

Follow https://channels.readthedocs.io/en/latest/installation.html

  1. python -m pip install -U channels
  2. Add channels to installed apps
    INSTALLED_APPS = (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        ...
        'channels',
    )
    
  3. create default routing file ChatServerPlayground/routing.py
    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    from channels.security.websocket import AllowedHostsOriginValidator
    from django.urls import path
    application = ProtocolTypeRouter({
    	'websocket': AllowedHostsOriginValidator(
    		AuthMiddlewareStack(
    			# URLRouter([...]) # Empty for now because we don't have a consumer yet.
    		)
    	),
    })
    
    Learn more here: ProtocolTypeRouter, AllowedHostsOriginValidator, AuthMiddlewareStack and URLRouter
  4. set your ASGI_APPLICATION in settings.py
    ASGI_APPLICATION = "ChatServerPlayground.routing.application"
    
  5. Now you create Consumers and add to the URLRouter list.

More Repositories

1

Android-Instagram-Clone

Develop your own Instagram Clone App
Java
921
star
2

Open-API-Android-App

Kotlin, MVI, Hilt, Retrofit2, Coroutines, Room Persistence, REST API, Token Authentication
Kotlin
688
star
3

MVVMRecipeApp

Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Retrofit2
Kotlin
542
star
4

Clean-Notes

Clean Architecture by layer
Kotlin
540
star
5

Dota-Info

Multi-module, Kotlin, MVI, Compose, Hilt, Navigation Component, Use-cases, SQL-Delight, Ktor
Kotlin
391
star
6

Food2Fork-KMM

Kotlin Multiplatform project that gets network data from Food2Fork.ca
Kotlin
369
star
7

Dagger-Examples

Some dagger-android examples with Retrofit2, MVVM architecture, RxJava, (Java)
Java
278
star
8

Dagger-Hilt-Playerground

A playground for learning dagger hilt on android
Kotlin
275
star
9

Google-Maps-2018

Google maps, directions, markers, clusters, custom icons, real-time gps updates (like uber) and more
Java
271
star
10

EspressoUITest-Examples

Examples of UI Testing with Espresso, Mockk, androidx.test
Kotlin
250
star
11

food2fork-compose

Kotlin, MVVM, Navigation Component, Hilt, Jetpack Compose, Retrofit2, Room, Use cases, Unit Testing
Kotlin
225
star
12

Navigation-Components-Example

An example using a single activity, several fragments, animations, arguments, with Navigation Components (Kotlin)
Kotlin
215
star
13

Local-db-Cache-Retrofit-REST-API-MVVM

App that interacts with a REST API using Retrofit. There is a local db cache and architecture is MVVM
Java
187
star
14

CodingWithMitch-Blog-Course

Web development with Django (Python) for Beginners
JavaScript
168
star
15

Video-Player-RecyclerView

Auto play videos in a RecyclerView with ExoPlayer like YouTube does
Java
160
star
16

HOWTO-django-channels-daphne

A how-to document outlining how to publish a django website equipped with WebSockets using Django Channels.
154
star
17

TabianCustomCamera

Custom camera for android using camera2 api (DEPRECATED)
Java
152
star
18

RestApiMVVM

App that interacts with a Rest Api. Architecture is MVVM.
Java
151
star
19

MVIExample

A simple MVI Architecture example
Kotlin
146
star
20

Spotify-Clone

Audio streaming application with MediaBrowserServiceCompat, ExoPlayer and Firestore
Java
139
star
21

Recyclerview

How to use a recyclerview
Java
131
star
22

Google-Maps-Google-Places

Android Google Maps API & Google Places API Course
Java
130
star
23

CodingWithMitchBlog-REST-API

A continuation of the CodingWithMitchBlog course. Adding a REST API using Django REST-framework
JavaScript
127
star
24

SQLite-for-Beginners-2019

SQLite on Android with Room Persistence Library (beginner course)
Java
120
star
25

MVVMExample1

A simple of example of MVVM in Android with LiveData and MutableLiveData
Java
113
star
26

KMM-Playground

Playground for learning Kotlin Multiplatform Mobile
Kotlin
113
star
27

Sending-and-Receiving-Data-with-Bluetooth

Java
85
star
28

Kotlin-Coroutine-Examples

Examples for using Coroutines
Kotlin
80
star
29

DaggerMultiFeature

Multi-feature app using dagger for learning purposes
Kotlin
70
star
30

ForSale

Android classified applications using ElasticSearch
Java
66
star
31

Unit-Testing-2

Unit Testing with JUnit5, JUnit4, Mockito, MVVM (repository pattern), Room Persistence, RxJava, (Java)
Java
60
star
32

SaveReadWriteDeleteSQLite

How to Save/Read/Write/Delete data from SQLite database Android
Java
57
star
33

Kotlin-RecyclerView-Example

Simple example with a RecyclerView that displays images and text with Kotlin, Glide and CardViews
Kotlin
52
star
34

Kotlin-Singleton-Example

Example of creating Singletons with Kotlin with some MVVM architecture
Kotlin
49
star
35

Bound-Services-with-MVVM

A simple example of how to bind an activity to a service while using MVVM
Java
49
star
36

FirestoreChatApp

Simple real-time chat application using Firestore
Java
46
star
37

TabFragments

How to use Tabs in Android Application
Java
40
star
38

Reddit-RSS-App

how to create a reddit app in Android
Java
39
star
39

Google-Maps-Compose

Example using Google maps with compose. This uses GoogleMap composable and MapEffect.
Kotlin
39
star
40

DataBindingGettingStarted

Getting started with data binding for Android
Java
37
star
41

AppBarLayouts

How to add an App Bar on the bottom and top of your Android app
Java
37
star
42

Bluetooth---How-to-Pair

How to pair with a bluetooth device in your android applications
Java
33
star
43

Retrofit-Caching-Example

An example of how to use Retrofit2 to cache HTTP responses
Java
33
star
44

EspressoDaggerExamples

UI Testing with Jetpack and AndroidX
Kotlin
33
star
45

Flows-and-Channels

Playground for Kotlin Flows and Channels
Kotlin
31
star
46

MVVM-Koin-Repository-Pattern

Experimenting with MVVM, Koin and Repository pattern in a simple TODO app.
Kotlin
30
star
47

Giffit

Kotlin
29
star
48

Dictionary

Dictionary app for Threads course on Pluralsight
Java
27
star
49

Flutter-Recipes-App

This will be a Flutter copy of the repository: "Local-db-Cache-Retrofit-REST-API-MVVM"
Dart
26
star
50

EnableBluetooth

Enabling and disabling Bluetooth in Android Studio
Java
25
star
51

ListViews

How to use ListViews
Java
25
star
52

Kotlin-Multiplatform-Utility

A repository containing useful classes for Kotlin Multiplatform projects
Kotlin
25
star
53

ComposePlayground

Playground for learning Jetpack Compose
Kotlin
25
star
54

FirestoreGettingStarted

Getting started with Firebase Cloud Firestore
Java
23
star
55

RxJava-FlatMap-Example

Getting data from multiple sources using a FlatMap Operator
Java
23
star
56

Bluetooth---Discover-Devices

Discovering bluetooth devices
Java
23
star
57

ABTestLayouts

Serve a Compose UI or an XML UI depending on Firebase remote config.
Kotlin
22
star
58

SwipeMenuListView

Android SwipeMenuListView example
Java
22
star
59

Android-SQLite-Beginner-Course

All source code for the Android SQLite Beginner Course
Java
22
star
60

TabianConsulting

Firebase on Android series on Pluralsight
Java
21
star
61

GesturesGettingStarted

Starting point for Android Gestures introduction
Java
20
star
62

SwipingViewPager

example of using a viewpager to swipe through product variations
Java
18
star
63

DatePickerDialog

how to add a DatePickerDialog popup to your android app
Java
18
star
64

Fragments

How to use Fragments in your Android Apps
Java
18
star
65

UI-Communication-with-MVI

Effective UI Communication with MVI architecture, a BaseActivity and the Repository Pattern.
Kotlin
18
star
66

Pie-Chart-Tutorial

MPAndroidChart Library
Java
17
star
67

FirebaseDirectMessage

Send Firebase Cloud Messages using a Firebase Cloud Function
Java
17
star
68

MotionLayout-Examples

Some examples using Androids new MotionLayout
Kotlin
17
star
69

FlutterPlayground

Playing around with flutter
Dart
16
star
70

Firebase-Read-Database

Learn how to read data from a firebase database
Java
16
star
71

CleanMultiModule

Multi-module playground with Compose, Hilt, Nav Component
Kotlin
16
star
72

OpenChat

Real-time chat android app to communicate with open-chat.xyz.
Kotlin
15
star
73

DialogFragmentToFragment

Capture data from a dialog fragment and send it to a fragment
Java
15
star
74

FirebasePushNotificationTopics

How to send push notifications to specifc topics
Java
15
star
75

ImportFromExcel

How to import data from excel into your Android Application
Java
14
star
76

EditableListView

Java
14
star
77

FragmentToFragmentCommunication

How to communicate between fragments and activities
Java
14
star
78

Android-Apps-with-Kotlin-SharedPreferences-and-Settings-Screens

Pluralsight course: Android Apps with Kotlin: SharedPreferences and Settings Screens
Kotlin
13
star
79

TabianDating

Android Keyboard Inputs: Getting Started
Java
13
star
80

MVI-Beginner-Example

An example using MVI architecture for beginners.
Kotlin
12
star
81

Memory-Leaks-on-Android

Memory leaks example for android
Java
12
star
82

CardView

how to create a CardView and use it in a ListView
Java
12
star
83

CodingWithMitchStore

Source code for Android Gestures Pluralsight Course
Java
12
star
84

ForSale-Starting-Point

A starting point for the ForSale repository
Java
12
star
85

GoogleMaps2018-Test

test application for google maps course
Java
11
star
86

Food2Fork

Project repo for Food2Fork.ca
Python
11
star
87

Retrofit

Retrofit Tutorials for Android
Java
11
star
88

Android-Studio-Settings

information on my android studio settings
11
star
89

Spotify-MVVM-MVI-Showcase

Kotlin
11
star
90

DialogFragmentToActivity

Capture data from a dialog fragment and send it to an activity
Java
11
star
91

Sockets-Playground

Playground for learning how to use sockets on android (realtime chat)
Java
11
star
92

FirebaseOnClickPushNotification

How to open an Activity when a Push Notification is clicked
Java
11
star
93

PhoneTest

Retrieve device properties, display properties and OS
Java
11
star
94

AndroidImageCropper-Example

Android image cropping example with a great 3rd party library
Kotlin
11
star
95

Firebase-Save-Images

How to save images to your firebase database
Java
11
star
96

BottomNav-MultipleBackstacks-NavigationComponent

playground setting up a bottom navigation with multiple backstacks using navigation component
Kotlin
10
star
97

Firebase-Save-User-Information

How to save user information into your firebase database
Java
10
star
98

MirrorTest

Android Developer Test
Java
10
star
99

NoteKeeper

Application for Kotlin course on SharedPreferences and Preferences Framework
Kotlin
10
star
100

Enable-Bluetooth-Discoverability

Enable bluetooth discoverability is android studio
Java
10
star