Skip to content
Luke Chen edited this page May 21, 2021 · 28 revisions

Installation

https://www.djangoproject.com/download/

$ pip install Django==3.1.7
$ python
Python 3.8.5 (default, Sep  4 2020, 07:30:14) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
3.1.7

Upgrade to the latest

$ python -m pip install -U Django
$ python -m django --version
3.2.3

Getting started

https://www.djangoproject.com/start/

Tutorial

https://docs.djangoproject.com/en/3.2/intro/tutorial01/

Network Config

UFW Firewall Rules

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-18-04 https://linuxize.com/post/how-to-list-and-delete-ufw-firewall-rules/

$ sudo ufw status verbose

$ sudo ufw enable

$ sudo ufw default deny incoming

$ sudo ufw allow 8899

Go to mysmypoll/settings.py, and add to ALLOWED_HOSTS

ALLOWED_HOSTS = ['xxx.xxx.xxx.xxx', 'localhost', '127.0.0.1']

Setup

To create a site

$ pwd
/home/lchen154/workspace/django
$ django-admin startproject mypoll

To run tests

$ python -Wa manage.py test

To run server

# to listen on default port 8000
python manage.py runserver

# to listen on a specific port
python manage.py runserver 8899

# to listen on all available public IPs
python manage.py runserver 0:8899

Internally, go to visit http://127.0.0.1:8899/

Create app

Create the "polls" app

$ python manage.py startapp polls

Add the "index" view to polls/views.py

polls/views.py¶
from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

Create a URLconf in the polls directory, create a file called urls.py.

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

And, point the URLconf at the polls.urls module, in mysite/urls.py.

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

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Now, run http://127.0.0.1:8899/polls/

Connect to MySQL

Modify 'mypoll/settings.py'

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mypolldb',
        'USER': 'mysqluser1',
        'PASSWORD': 'testtest1',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

Clone this wiki locally