Django 开发环境的搭建和创建 website工程
要开始 Django 开发,你需要从中掌握以下知识:
- 如何创建 Django 工程,并了解 Django 默认的工程目录结构
- 如何创建 Django APP
- 理解 Django 的MTV 模式,学会编写 Model、View、Template
- Django 如何处理静态文件,即各种 CSS,JS,以及图片文件等
一:环境配置
1.Centos
[[email protected] myweb]# uname -a
Linux localhost.localdomain 3.10.0-514.10.2.el7.x86_64 #1 SMP Fri Mar 3 00:04:05 UTC 2017 x86_64 x86_64 x86_64
2.Apache
[[email protected] myweb]# httpd -v
Server version: Apache/2.4.6 (CentOS)
Server built: Nov 14 2016 18:04:44
3.mysql
# wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm
# rpm -ivh mysql-community-release-el7-5.noarch.rpm
# yum install mysql-community-server
#systemctl start mysql.service
[[email protected] ~]# mysql -v
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.6.35 MySQL Community Server (GPL)
4.python3.6.1RC
#创建command软链接
ln -s /usr/local/python3/bin/django-admin.py /usr/local/bin/django-admin.py
5.django
python -m django --version
二:创建website项目
1.创建myweb
[[email protected] ]# cd /home
[[email protected] home]# mkdir website
[[email protected] home]# cd website
[[email protected] website]# django-admin.py startproject myweb
[[email protected] website]# ls
myweb
[[email protected] website]# cd myweb
[[email protected] myweb]# ls
manage.py myweb
#manage.py >> 一个命令行工具,可以使你用多种方式对Django项目进行交互。
#myweb >> 外层的myweb/根目录仅仅是项目的一个容器
[[email protected] myweb]# cd myweb
[[email protected] myweb]# ls
__init__.py settings.py urls.py wsgi.py
#__init__.py:一个空文件,它告诉Python这个目录应该被看做一个Python包
#settings.py:该Django 项目的设置/配置
# urls.py:该Django项目的URL声明;你的Django站点的“目录”。
# wsgi.py:用于你的项目的与WSGI兼容的Web服务器入口。
[[email protected] myweb]# python manage.py runserver 0.0.0.0:8090
# python manage.py runserver 0.0.0.0:8090 启动服务在8090端口
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run ‘python manage.py migrate‘ to apply them.
March 19, 2017 - 07:21:44
Django version 1.10.6, using settings ‘myweb.settings‘
Starting development server at http://0.0.0.0:8090/
Quit the server with CONTROL-C.
Invalid HTTP_HOST header: ‘192.168.2.18:8090‘. You may need to add ‘192.168.2.18‘ to ALLOWED_HOSTS.
[19/Mar/2017 07:21:56] "GET / HTTP/1.1" 400 60438
Invalid HTTP_HOST header: ‘192.168.2.18:8090‘. You may need to add ‘192.168.2.18‘ to ALLOWED_HOSTS.
[19/Mar/2017 07:21:56] "GET /favicon.ico HTTP/1.1" 400 60360
Invalid HTTP_HOST header: ‘192.168.2.18:8090‘. You may need to add ‘192.168.2.18‘ to ALLOWED_HOSTS.
[19/Mar/2017 07:21:56] "GET /favicon.ico HTTP/1.1" 400 60420
根据提示在settings.py里添加:ALLOWED_HOSTS = [‘192.168.2.18‘,‘localhost‘,‘127.0.0.1‘]解决
再次打开正常
2.创建webapp
[[email protected] myweb]# python manage.py startapp webtest
[[email protected] myweb]# ls
db.sqlite3 manage.py myweb webtest
[[email protected] myweb]# cd webtest
[[email protected] webtest]# ls
admin.py apps.py __init__.py migrations models.py tests.py views.py
3.配置mysql
[[email protected] webtest]# systemctl enable mysqld
#开机启动
[[email protected] webtest]# mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.6.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective owners.
Type ‘help;‘ or ‘\h‘ for help. Type ‘\c‘ to clear the current input statement.
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> set password for ‘root‘@‘localhost‘ =password(‘Shuai_sqj‘);
Query OK, 0 rows affected (0.01 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql> GRANT ALL PRIVILEGES ON *.* TO ‘web‘@‘%‘ IDENTIFIED BY ‘Shuai_sqj‘ WITH GRANT OPTION;
grant all privileges on *.* to [email protected]‘%‘identified by ‘Shuai_sqj‘;
#允许远程访问
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges
-> \q
Bye
mysql> select host,user from mysql.user;
+-----------------------+-------+
| host | user |
+-----------------------+-------+
| % | myweb |
| 127.0.0.1 | root |
| ::1 | root |
| localhost | |
| localhost | root |
| localhost.localdomain | |
| localhost.localdomain | root |
+-----------------------+-------+
7 rows in set (0.00 sec)
mysql> create user ‘web‘@‘%‘ identified by ‘Shuai_sqj‘;
#创建一个新的用户
[[email protected] ~]# systemctl status mysqld.service
#查看运行状态
● mysqld.service - MySQL Community Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Sun 2017-03-19 05:31:32 EDT; 12s ago
Process: 1424 ExecStartPost=/usr/bin/mysql-systemd-start post (code=exited, status=0/SUCCESS)
Process: 867 ExecStartPre=/usr/bin/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
Main PID: 1423 (mysqld_safe)
CGroup: /system.slice/mysqld.service
├─1423 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
└─1799 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/lo...
Mar 19 05:31:28 localhost.localdomain systemd[1]: Starting MySQL Community Server...
Mar 19 05:31:29 localhost.localdomain mysqld_safe[1423]: 170319 05:31:29 mysqld_safe Logging to ‘/var/log/mysqld.log‘.
Mar 19 05:31:29 localhost.localdomain mysqld_safe[1423]: 170319 05:31:29 mysqld_safe Starting mysqld daemon with databases fro...mysql
Mar 19 05:31:32 localhost.localdomain systemd[1]: Started MySQL Community Server.
Hint: Some lines were ellipsized, use -l to show in full.
新建一个名为webtest的数据库
4.配置settings.py 数据库
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: ‘webtest‘,
‘USER‘: ‘web‘,
‘PASSWORD‘: ‘Shuai_sqj‘,
‘HOST‘: ‘192.168.2.18‘,
‘PORT‘: ‘3306‘,
}
}
#在配置之前首先要pip install pymysql
myweb/__int__.py 导入
import pymysql
pymysql.install_as_MySQLdb()
二:编写Models
Model 对应数据库,我们编写的是一个 Blog 应用,因此数据库中应该存放 Blog 下的文章(Aticle),文章由标题(title)、正文(body)、发布时间(publised_time)等组成。先看 django 是如何定义数据库的,之后再逐行解释代码(假设你已经对 django 的工程目录结构了解了,我们一般把 Model 定义在 models.py 文件中):
from django.db import models
# Create your models here.
class Article(models.Model):
STATUS_CHOICES = (
(‘d‘, ‘Draft‘),
(‘p‘, ‘Published‘),
)
title = models.CharField(‘标题‘, max_length=70)
body = models.TextField(‘正文‘)
created_time = models.DateTimeField(‘创建时间‘, auto_now_add=True)
last_modified_time = models.DateTimeField(‘修改时间‘, auto_now=True)
status = models.CharField(‘文章状态‘, max_length=1, choices=STATUS_CHOICES)
abstract = models.CharField(‘摘要‘, max_length=54, blank=True, null=True, help_text="可选,如若为空将摘取正文的前54个字符")
views = models.PositiveIntegerField(‘浏览量‘, default=0)
likes = models.PositiveIntegerField(‘点赞数‘, default=0)
topped = models.BooleanField(‘置顶‘, default=False)
category = models.ForeignKey(‘Category‘, verbose_name=‘分类‘, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.title
class Meta:
ordering = [‘-last_modified_time‘]
class Category(models.Model):
name = models.CharField(‘类名‘, max_length=20)
created_time = models.DateTimeField(‘创建时间‘, auto_now_add=True)
last_modified_time = models.DateTimeField(‘修改时间‘, auto_now=True)
def __str__(self):
return self.name
##########################---------分---------割--------线---------#############################
逐行解释:
from django.db import models
# 和 model 相关的一些API定义在 django.db.models 模块中
class Article(models.Model):
"""
所有的 model 必须继承自django.db.models
类 Aticle 即表示 Blog 的文章,一个类被 diango 映射成数据库中对应的一个表,表名即类名
类的属性(field),比如下面的 title、body 等对应着数据库表的属性列
"""
STATUS_CHOICES = (
(‘d‘, ‘Draft‘),
(‘p‘, ‘Published‘),
)
# 在 status 时说明
title = models.CharField(‘标题‘, max_length=70)
# 文章标题,CharField 表示对应数据库中表的列是用来存字符串的,‘标题‘是一个位置参数
# (verbose_name),主要用于 django 的后台系统,不多做介绍。max_length 表示能存储的字符串
# 的最大长度
body = models.TextField(‘正文‘)
# 文章正文,TextField 用来存储大文本字符
created_time = models.DateTimeField(‘创建时间‘, auto_now_add=True)
# 文章创建时间,DateTimeField用于存储时间,设定auto_now_add参数为真,则在文章被创建时会自动添加创建时间
last_modified_time = models.DateTimeField(‘修改时间‘, auto_now=True)
# 文章最后一次编辑时间,auto_now=True表示每次修改文章时自动添加修改的时间
status = models.CharField(‘文章状态‘, max_length=1, choices=STATUS_CHOICES)
# STATUS_CHOICES,field 的 choices 参数需要的值,choices选项会使该field在被渲染成form时被渲染为一个select组件,这里我定义了两个状态,一个是Draft(草稿),一个是Published(已发布),select组件会有两个选项:Draft 和 Published。但是存储在数据库中的值分别是‘d‘和‘p‘,这就是 choices的作用。
abstract = models.CharField(‘摘要‘, max_length=54, blank=True, null=True,help_text="可选,如若为空将摘取正文的前54个字符")
# 文章摘要,help_text 在该 field 被渲染成 form 是显示帮助信息
views = models.PositiveIntegerField(‘浏览量‘, default=0)
# 阅览量,PositiveIntegerField存储非负整数
likes = models.PositiveIntegerField(‘点赞数‘, default=0)
# 点赞数
topped = models.BooleanField(‘置顶‘, default=False)
# 是否置顶,BooleanField 存储布尔值(True或者False),默认(default)为False
category = models.ForeignKey(‘Category‘, verbose_name=‘分类‘,
null=True,
on_delete=models.SET_NULL)
# 文章的分类,ForeignKey即数据库中的外键。外键的定义是:如果数据库中某个表的列的值是另外一个表的主键。外键定义了一个一对多的关系,这里即一篇文章对应一个分类,而一个分类下可能有多篇 文章。详情参考django官方文档关于ForeinKey的说明,on_delete=models.SET_NULL表示删除某个分类(category)后该分类下所有的Article的外键设为null(空)
def __str__(self):
# 主要用于交互解释器显示表示该类的字符串
return self.title
class Meta:
# Meta 包含一系列选项,这里的 ordering 表示排序,- 号表示逆序。即当从数据库中取出文章时,其是按文章最后一次修改时间逆序排列的。
ordering = [‘-last_modified_time‘]
class Category(models.Model):
"""
另外一个表,存储文章的分类信息
"""
name = models.CharField(‘类名‘, max_length=20)
created_time = models.DateTimeField(‘创建时间‘, auto_now_add=True)
last_modified_time = models.DateTimeField(‘修改时间‘, auto_now=True)
def __str__(self):
return self.name