1.创建项目project
django-admin.py startproject myblog
查看目录树
alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'"
2.创建应用app
一个工程里可以创建很多个应用app, 一个app就是一个功能模块,我们创建一个blog应用:
cd myblog 打开目录
python manage.py startapp blog 创建名为blog的app
此时目录为:
|____blog | |______init__.py | |____admin.py | |____apps.py | |____migrations | | |______init__.py | |____models.py | |____tests.py | |____views.py |____manage.py |____myblog | |______init__.py | |______init__.pyc | |____settings.py | |____settings.pyc | |____urls.py | |____wsgi.py
将新建的blog加入到工程中,打开myblog/setting.py添加blog
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ]
启动工程:python manage.py runserver
3.连接数据库
在setting.py中进行数据库配置
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'blog', } }
同时将时区设置为
TIME_ZONE = 'Asia/Shanghai'
上文中有测试数据库连接是否成功的方法。
4.创建Model
django框架不需要手动在数据库创建数据表,而是通过models.py文件创建
# -*- coding: utf-8 -*- from django.db import models # Create your models here. class Tag(models.Model): tag_name = models.CharField('标签', max_length=50) tag_cn_name = models.CharField('中文名字', max_length=50, blank=True) def __unicode__(self): return self.tag_name class Article(models.Model): title = models.CharField('标题', max_length=100) tag = models.ManyToManyField(Tag, max_length=50, blank=True) date_time = models.DateTimeField('日期', auto_now_add=True) content = models.TextField('内容', blank=True, null=True) def __unicode__(self): return self.title class Meta: verbose_name = '文章' verbose_name_plural = '文章' ordering = ['-date_time']
5.同步数据库
python manage.py makemigrations
输出
Migrations for 'blog': 0001_initial.py: - Create model Article - Create model Tag - Add field tag to article
输入:
python manage.py migrate
输出:
Operations to perform:
Apply all migrations: admin, blog, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
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 blog.0001_initial... OK
Applying sessions.0001_initial... OK
表示同步数据库成功
6.设置后台管理系统
在admin.py中添加创建的数据表,从而在后台管理页面中看到
from django.contrib import admin from blog.models import Tag, Article # Register your models here. admin.site.register(Tag) admin.site.register(Article)
启动python manage.py runserver
浏览器中输入http://127.0.0.1:8000/admin