安裝Django:http://www.runoob.com/django/django-install.html
下面介紹一下連接MySQL數據庫:
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數據庫:
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、模型安裝
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