一、安装django
sudo pip install Djangosudo apt install sqlite3
sqlite3后面Django Admin 管理工具要用到。
二、创建 HelloWorld 项目:django-admin startproject HelloWorld
并进入项目目录: cd HelloWorld/
三、修改urls.py:vi HelloWorld/urls.py
"""HelloWorld URL ConfigurationThe `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/Examples:Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))"""from django.conf.urls import urlfrom django.contrib import adminfrom . import viewurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/$', view.index), url(r'^$', view.hello),]
四、新建一个 view.py 文件:vi HelloWorld/view.py
#coding=utf-8from django.http import HttpResponsefrom django.shortcuts import renderdef hello(request): return HttpResponse("Hello world ,你好世界! ")def index(request): context = {} return render(request, 'myapp/index.html', context)
五、启用Django Admin 管理工具:
$ python manage.py migrate$ python manage.py createsuperuserUsername (leave blank to use 'xxxxxxx'): Email address: xxxxx@xxxxxxPassword:q1w2e3r4 Password (again): q1w2e3r4Superuser created successfully.
六、修改settings.py中TEMPLATE:vi HelloWorld/settings.py
将TEMPLATE中的'DIRS': [],修改为:'DIRS': [os.path.join(BASE_DIR,'templates')]
修改后如下:TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
修改数据库配置也在这里如把sqlite3改为pg:
DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # 'ENGINE': 'django.db.backends.mysql', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'testdb',#数据库名称 'USER':'postgres',#拥有者,这个一般没修改 'PASSWORD':'****',#密码,自己设定的 'HOST':'127.0.0.1',# 'PORT':'5432', }
七、页面
~/HelloWorld$mkdir templates
~/HelloWorld$vi templates/base.html
菜鸟教程(runoob.com) Hello World!
菜鸟教程 Django 测试。
{% block mainbody %}original
{% endblock %}
~/HelloWorld$mkdir templates/myapp
~/HelloWorld$vi templates/myapp/index.html
{% extends "base.html" %} {% block mainbody %}继承了 ../base.html 文件
{% endblock %}
八、项目目录结构:~$ tree
└── HelloWorld ├── db.sqlite3 ├── HelloWorld │ ├── __init__.py │ ├── __init__.pyc │ ├── __pycache__ │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── view.py │ ├── view.pyc │ ├── wsgi.py │ └── wsgi.pyc ├── manage.py ├── readme.txt └── templates ├── base.html └── myapp └── index.html
九、启动项目:
$ python manage.py runserver 0.0.0.0:8000Performing system checks...System check identified no issues (0 silenced).July 07, 2018 - 14:02:47Django version 1.11.14, using settings 'HelloWorld.settings'Starting development server at http://0.0.0.0:8000/Quit the server with CONTROL-C.
十、浏览器中访问
1、http://127.0.0.1:8000/index
会调用 view.py中index方法,并转向:templates/myapp/index.html。
2、http://127.0.0.1:8000/调用 view.py中hello方法
3、http://127.0.0.1:8000/admin进入Django Site administration管理登入页面:输入上面第五点的用户名、密码。
十一、读取数据库并显示在前端
1、追加models:vi HelloWorld/models.py
from __future__ import unicode_literalsfrom django.db import models# Create your models here.class Employee(models.Model): name=models.CharField(max_length=20)
2、修改INSTALLED_APPS字段加上 HelloWorld:$ vi HelloWorld/settings.py
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'HelloWorld',]
3、下面两条命令执行后在数据库里建了HelloWorld_employee表:
~/HelloWorld$ python manage.py makemigrations HelloWorldMigrations for 'HelloWorld': HelloWorld/migrations/0001_initial.py - Create model Employee~//HelloWorld$ python manage.py migrateOperations to perform: Apply all migrations: HelloWorld, admin, auth, contenttypes, sessionsRunning migrations: Applying HelloWorld.0001_initial... OK
4、数据库表中追加数据
~/HelloWorld$ sqlite3 db.sqlite3sqlite> .schema HelloWorld_employeeCREATE TABLE "HelloWorld_employee" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(20) NOT NULL);sqlite> INSERT INTO HelloWorld_employee(id, name) VALUES (1, '萝莉1');sqlite> INSERT INTO HelloWorld_employee(id, name) VALUES (2, '萝莉2');sqlite>
5、修改urls.py追加条目table:vi HelloWorld/urls.py
from django.conf.urls import urlfrom django.contrib import adminfrom . import viewurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/$', view.index), url(r'^table/$',view.table,name='table') , url(r'^$', view.hello),]
python3的路由写法有点不同:
urlpatterns = [ path('admin/', admin.site.urls), path('table/', view.table, name='table'), path('index/', view.index), path('', view.hello),]
6、 view.py 中追加table方法:vi HelloWorld/view.py
#coding=utf-8from django.http import HttpResponsefrom django.shortcuts import renderfrom django.shortcuts import HttpResponseRedirect,Http404,HttpResponse,render_to_responsefrom .models import Employeedef hello(request): return HttpResponse("Hello world ,你好世界! ")def index(request): context = {} return render(request, 'myapp/index.html', context)def table(request): names=Employee.objects.all() #获取我们的数据库信息到names里 return render_to_response("table.html",locals())
7、增加页面vi templates/table.html
显示雇员 雇员名单
{% for name in names %}{
{name.id}} : { {name.name}} {% endfor %}
项目结构:
├── HelloWorld│ ├── db.sqlite3│ ├── HelloWorld│ │ ├── __init__.py│ │ ├── __init__.pyc│ │ ├── migrations│ │ │ ├── 0001_initial.py│ │ │ ├── 0001_initial.pyc│ │ │ ├── __init__.py│ │ │ └── __init__.pyc│ │ ├── models.py│ │ ├── models.pyc│ │ ├── __pycache__│ │ ├── settings.py│ │ ├── settings.pyc│ │ ├── urls.py│ │ ├── urls.pyc│ │ ├── view.py│ │ ├── view.pyc│ │ ├── wsgi.py│ │ └── wsgi.pyc│ ├── manage.py│ ├── readme.txt│ └── templates│ ├── base.html│ ├── myapp│ │ └── index.html│ └── table.html
8、运行截图http://127.0.0.1:8000/table: