安装Django:http://www.runoob.com/django/django-install.html
下面介绍一下连接MySQL数据库:
1、使用 django-admin.py 来创建 HelloWorld 项目:
django-admin.py startproject HelloWorld
创建完成后我们可以查看下项目的目录结构:
[root@localhost /]# cd HelloWorld/
[root@localhost HelloWorld]# tree #如果没有tree,就安装一个yum install tree
.
├── books
│ ├── admin.py
│ ├── admin.pyc
│ ├── apps.py
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0001_initial.pyc
│ │ ├── __init__.py
│ │ └── __init__.pyc
│ ├── models.py
│ ├── models.pyc
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── HelloWorld
│ ├── __init__.py
│ ├── __init__.pyc
│ ├── settings.py
│ ├── settings.pyc
│ ├── urls.py
│ ├── urls.pyc
│ ├── wsgi.py
│ └── wsgi.pyc
└── manage.py
3 directories, 23 files
目录说明:
- HelloWorld: 项目的容器。
- manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。
- HelloWorld/__init__.py: 一个空文件,告诉 Python 该目录是一个 Python 包。
- HelloWorld/settings.py: 该 Django 项目的设置/配置。
- HelloWorld/urls.py: 该 Django 项目的 URL 声明; 一份由 Django 驱动的网站"目录"。
- HelloWorld/wsgi.py: 一个 WSGI 兼容的 Web 服务器的入口,以便运行你的项目。
python manage.py runserver 0.0.0.0:8000
如果报错的话:去HelloWorld/settings.py 中 ALLOWED_HOSTS添加 ip 或者添加 *
浏览器访问 ip:8000,成功显示:
连接MySQL数据库:
1、进入项目根目录,创建books
python manage.py startapp books
2、创建模型:
vim books models.py
添加一下内容:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
3、模型安装
修改HelloWorld下的配置文件 settings.py
4、验证模型的有效性
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME' : 'test',
'USER' : 'root',
'PASSWORD':'',
'HOST': '127.0.0.1',
}
}
4、验证模型的有效性
python manage.py check
python manage.py makemigrations books
python manage.py sqlmigrate books 0001
7、用于执行迁移动作
python manage.py migrate
执行完。查看MySQL数据库: