Django初次使用
###一、安装
pip install django
###二、创建项目
找到放置项目的目录。
django-admin startproject jdango_demo
目录结构
.
├── db.sqlite3
├── django_demo
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ ├── settings.cpython-36.pyc
│ │ ├── urls.cpython-36.pyc
│ │ └── wsgi.cpython-36.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
目录说明:
- django_demo:项目的容器
- manage.py:命令工具,与项目进行交互的命令行工具集的入口,项目管理器。执行python manage.py查看所有命令。
- init.py:空文件,声明模块的文件。
- settings.py:Django项目的设置/配置
- urls.py:Django项目的URL声明、一份由 Django 驱动的网站"目录"
- wsgi.py:WSGI(Python Web Server Gateway Interface)Python服务器网关接口,Python应用与Web服务器之间的接口。
###三、项目启动
python manage.py runserver 0.0.0.0:8000
###四、创建应用:blog
python manage.py startapp blog
将应用名添加到settings.py中的INSTALLED_APPS里
blog目录
├── __init__.py
├── admin.py
├── apps.py
├── migrations
│ ├── __init__.py
├── models.py
├── tests.py
└── views.py
- migrations:数据移植模块,内容自动生成。
- admin:当前应用的后台管理系统配置。
- apps:改应用的一些配置(1.9版本后自动生成)
- models:数据模块,使用ORM模块。
- tests.py:自动化测试模块,编写测试脚本。
- views.py:执行相应的代码所在模块,代码逻辑处理的主要地点,大部分代码在这里编写。
创建第一个响应页面
编辑blog.views
每个响应对应一个函数,函数必须返回一个响应。
函数必须存在一个参数,一般约定为request
每个响应函数对应一个URL
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse('Hello word!')
接下来配置urls.py,url函数存放在urlpatterns中。
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
]
第二种url配置
注意:根urls.py针对APP配置的URL名称,是该APP所有的URL的总路径。
在根urls.py中引入include
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls'))
]
在APP目录下创建urls.py文件,格式与根urls.py相同。
from django.urls import path
from . import views
# 该blog模块中的总url
urlpatterns = [
path(r'', views.index),
]
创建HTML文件
在blog目录下创建文件夹templates文件夹,创建文件index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{hello}}</h1>
</body>
</html>
然后修改views.py文件
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# return HttpResponse('Hello word!')
return render(request, 'index.html', {'hello':'Hello, Blog'}) # 请求,模版文件,传递到前端的参数
#####Models介绍
一个Model对应数据库的一张数据表,Django中Model以类的形式表现,包含了一些基本字段及数据的一些行为。
**ORM:**对象关系映射
实现了对象和数据库之间的映射,隐藏了数据访问的细节,不需要编写SQL语句。
编写Models
在models.py文件中,引入models模块,创建类,继承models.Model,该类就是一张数据表,在类中穿件字段
字段创建:
字段即类里面的属性(变量)
attr = models.CharField(max_length=64) #max_length约束长度
生成数据表
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=32, default='Title')
content = models.TextField(null=True) # 允许为空
执行:python manage.py makemigrations
会在app/migrations目录下生成移植文件
在执行:python manage.py migrate
Mac:django_demo hubo$ python manage.py makemigrations
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Article
Mac:django_demo hubo$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying blog.0001_initial... OK
Applying sessions.0001_initial... OK
执行python manage.py sqlmigrate 应用名 文件id 查看sql语句
python manage.py sqlmigrate blog 0001
Mac:django_demo hubo$ python manage.py sqlmigrate blog 0001
BEGIN;
--
-- Create model Article
--
CREATE TABLE "blog_article" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(32) NOT NULL, "content" text NULL);
COMMIT;
默认sqlite3的数据库在项目根目录下的db.sqlite3
下载可视化工具添加数据后,将数据显示到前端。
from django.shortcuts import render
from django.http import HttpResponse
from . import models
# Create your views here.
def index(request):
article = models.Article.objects.get(pk=1)
return render(request, 'index.html', {'article': article})
五、Admin使用
Admin是Django自带的功能强大的自动化水管理界面,被授权的用户直接在Admin中管理数据库,提供了针对Admin的针对功能
配置用户
命令:python manage.py createsuperuser
密码:qwer1234(防止自己忘了。。)
Mac:django_demo hubo$ python manage.py createsuperuser
Username (leave blank to use 'hubo'): admin
Email address: admin@admin
Error: Enter a valid email address.
Email address: admin@admin.com
Password:
Password (again):
Superuser created successfully.
Mac:django_demo hubo$
**Admin入口:**http://localhost:8000/admin/
修改中文修改settings.py中LANGUAGE_CODE = ‘en-us’,为zh_Hans就成中文了
配置应用
在应用下的admin.py中引入自身的models模块(或模块的类)
编辑admin.py:admin.site.register(models.Article)
from django.contrib import admin
# Register your models here.
from . import models
admin.site.register(models.Article)
访问admin界面,可以在blog下面修改数据
博客页面设计
主页页面内容:文章标题列表,链接,发表博客。
博客文章页面:标题,内容,修改按钮。