Django 版本:3.x (https://www.djangoproject.com/)
Bootstrap 版本:3.3.5 (http://getbootstrap.com)
1. 系统配置
Ubuntu 18.04.5 LTS (x86_64)
MySQL Ver 14.14 Distrib 5.7.32, for Linux (x86_64)
Python 3.6.9
Pip 9.0.1
Django: 3.0
2. 创建 Django 项目
$ django-admin startproject 'djangoDemo'
3. 添加 app
$ cd djangoDemo
$ python manage.py startapp 'appDemo'
目录结构:
|-- djangoDemo
| |-- __init__.py
| |-- asgi.py
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
|-- appDemo
| |-- __init__.py
| |-- admin.py
| |-- apps.py
| |-- models.py
| |-- tests.py
| |-- views.py
| |-- migrations
| |-- __init__.py
|-- manage.py
修改 djangoDemo/settings.py
ALLOWED_HOSTS = ['localhost', '192.168.0.5'] # 根据所在主机的IP来设置
...
INSTALLED_APPS = [
...
'appDemo',
]
4. 运行项目
$ python manage.py runserver # 默认 localhsot,端口 8000
$ python manage.py runserver 192.168.0.5:8080 # 指定 host 和端口
5. 配置 MySQL 或 MariaDB (非必选项,本实例没用到数据库操作)
修改 djangoDemo/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangodemo',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
$ python manage.py makemigrations 'appDemo'
$ python manage.py migrate
6. 静态资源
1)修改djangoDemo/settings.py
# Develop environment
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
2) JQuery and Bootstrap
Bootstrap: https://getbootstrap.com/
JQuery:https://jquery.com/
目录结构:
|-- djangoDemo
|-- appDemo
|-- static
| |-- lib
| | |-- jquery
| | | |-- jquery-1.12.2.min.js
| | |-- bootstrap-3.3.5
| | |-- css
| | |-- js
| | |-- fonts
| |-- images
| |-- js
| |-- css
|-- manage.py
3) 添加 template 文件到 appDemo
|-- appDemo
|-- templates
|-- layout.html
|-- demo.html
layout.html 内容:
{% load static %}
{% block content %} Content Block {% endblock %}
demo.html 内容:
{% extends "layout.html" %}
{% block title %}Django demo page {% endblock %}
{% block content %}
First django demo page
console.log("First django demo page");
{% endblock %}
7. 视图和路由
1) 修改 appDemo/views.py
from django.shortcuts import render
# Create your views here.
def demo(request):
return render(request, "demo.html")
2) 修改 djangoDemo/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('demo/', include('appDemo.urls')),
]
3) 添加 appDemo/urls.py
from django.urls import path
from appDemo import views
urlpatterns = [
path('', views.demo),
]
8. 运行
$ python manage.py runserver 192.168.0.5:8080 # 指定 host 和端口
用浏览器访问 http://192.168.0.5:8080/demo