Skip to content

Instantly share code, notes, and snippets.

@kevin-shu
Last active April 5, 2024 10:51
Show Gist options
  • Save kevin-shu/d145403a9ff677927743222e059fa911 to your computer and use it in GitHub Desktop.
Save kevin-shu/d145403a9ff677927743222e059fa911 to your computer and use it in GitHub Desktop.
  1. Run django-admin startproject <project name>, you'll get a root folder and a project folder in it, they both called ""
  2. Create "apps", "static", "templates" folders in root folder.
  3. Edit setting.py in project folder, add dir path in it, like below:
# 设置模板目录
TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    },
]

# 设置静态文件目录
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
# For production. 
# Specify an absolute path to avoid any confusion about where Django will collect static files. 
# This path should be outside your Django project directory. For example:
STATIC_ROOT = '/var/www/example.com/static/'

Ref: https://rai-shahnawaz.medium.com/creating-a-django-project-the-right-way-14d230358d72

Create a APP

  1. run:
cd apps/
django-admin startapp <app name>
  1. Edit "name" in apps.py, adding "apps." before the original name.
    For example, changing name = 'post' to name = 'apps.post'
  2. Add this app into project by editting settings.py:
INSTALLED_APPS = [ 
    'django.contrib.admin', 
    'django.contrib.auth', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles' , 

    'apps.app_1', # <--- Here
]
  1. (Optional, but recommended) Create urls.py in app folder for better organization:
# myapp/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('about/', views.about, name='about'),
]
  1. Include urls of app by add it into urls.py:
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include  # 引入 include 函数
from apps.post import views # Import specific app 

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),  # Include app's urls
    path('', views.home), # Specific path of specific app
]

Env setting

Create a .env file in project root directory. The file format can be understood from the example below:

DEBUG=on
SECRET_KEY=your-secret-key
DATABASE_URL=psql://user:un-githubbedpassword@127.0.0.1:8458/database
SQLITE_URL=sqlite:///my-local-sqlite.db
CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213
REDIS_URL=rediscache://127.0.0.1:6379/1?client_class=django_redis.client.DefaultClient&password=ungithubbed-secret

And use it with settings.py as follows:

import environ
import os

env = environ.Env(
    # set casting, default value
    DEBUG=(bool, False)
)

# Set the project base directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

# False if not in os.environ because of casting above
DEBUG = env('DEBUG')

Ref: https://dev.to/defidelity/protect-your-sensitive-data-a-guide-to-env-files-in-django-499e

Requirements

django-environ==0.9.0
gunicorn==21.2.0

Nginx's setting

For static files:

server {
    ...
    location /static/ {
        alias /var/www/example.com/static/;
    }
    ...
}
server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /path/to/your/project;
    }

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Google App Engine

app.yaml:

# app.yaml
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT mysite.wsgi
# entrypoint: bash -c 'python3 manage.py migrate --noinput && gunicorn -b :$PORT app.wsgi'

beta_settings:
    cloud_sql_instances: PROJECT_ID:REGION:INSTANCE_NAME

runtime_config:
  python_version: 3.7

When you deploy to App Engine, the dependencies specified in the requirements.txt file will be installed automatically with your deployed app. You can use any Linux-compatible Python package, including packages that require native C extensions. Ref: https://cloud.google.com/appengine/docs/standard/python3/specifying-dependencies

Before delpoy

After moving to new domain

  1. Set ALLOWED_HOSTS

After pushing code

  1. Migration: python manage.py migrate
  2. Collect static files: django-admin collectstatic This will clone every static files in the project into STATIC_ROOT and those files should be served by web server (e.g. Nginx, Apache) for better performance.
  3. pip install -r requirements. txt

Deploy

  1. python3 manage.py check --deploy
  2. gunicorn myproject.wsgi:application --bind 0.0.0.0:8000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment