/Codingwithmitch-Chat

Real-time chat server with Django

Primary LanguageJavaScript

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.