开启新的项目
$ django-admin startproject blogsite(网站工程名称)
成功以后生成项目文件夹,结构如下
blogsite /
manage.py
blogsite /
__init__.py
settings.py
urls.py
wsgi.py
此时运行服务器
$ python manage.py runserver
在控制台看到如下信息
Performing system checks...
System check identified no issues (0silenced).
You have unapplied migrations; your app maynot work properly until they are applied.
Run `python manage.py migrate' to applythem.
July 25, 2016 - 15:50:53
Django version 1.9, using settings ` blogsite.settings'
Starting development server athttp://127.0.0.1:8000/
Quit the server with CONTROL-C.
此时打开浏览器,输入http://127.0.0.1:8000/,你将看到这样的信息
你也可以修改/blogsite/setting.py来更改语言和时区
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
再运行一遍服务器,刷新一下页面
然后我们创建一个app
$ python manage.py startapp blog
创建了一个文件夹blog,其内部结构如下
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
注册app
/blogsite/setting.py
# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
……
]
……
博客需要那些模型?
博文、博文分类、标签
根据你设计的类来修改
/blog/models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
@python_2_unicode_compatible #如果要求python2支持utf-8则需要加上此句
class Category(models.Model):
name = models.CharField(u'名称', max_length = 20)
def __str__(self):
return self.name;
@python_2_unicode_compatible
class Tag(models.Model):
name = models.CharField(u'名称', max_length = 20)
def __str__(self):
return self.name;
@python_2_unicode_compatible
class Article(models.Model):
title = models.CharField(u'标题',max_length = 150)
body = models.TextField(u'正文')
date = models.DateTimeField(u'发布时间')
category = models.ForeignKey(Category, verbose_name=u'分类')
tags = models.ManyToManyField(Tag, verbose_name = u'标签', blank=True)
# models.ForeignKey表示一个Article有一个Category
# models.ManyToManyField表示一个Article有多个Tag,blank=True表示可以为空
def __str__(self):
return self.title
写完之后要向数据库中注册,这里我们使用python自带的SQLite
先创建一个migration
$ python manage.py makemigrations blog然后写入数据库
$ python manage.py sqlmigrate blog 0001
控制台显示如下:
BEGIN;
--
-- Create model Article
--
CREATE TABLE "blog_article"("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title"varchar(150) NOT NULL, "body" text NOT NULL, "date"datetime NOT NULL);
--
-- Create model Category
--
CREATE TABLE "blog_category"("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name"varchar(20) NOT NULL);
--
-- Create model Tag
--
CREATE TABLE "blog_tag"("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name"varchar(20) NOT NULL);
--
-- Add field category to article
--
ALTER TABLE "blog_article" RENAMETO "blog_article__old";
CREATE TABLE "blog_article"("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title"varchar(150) NOT NULL, "body" text NOT NULL, "date"datetime NOT NULL, "category_id" integer NOT NULL REFERENCES"blog_category" ("id"));
INSERT INTO "blog_article"("body", "date", "category_id", "id","title") SELECT "body", "date", NULL,"id", "title" FROM "blog_article__old";
DROP TABLE "blog_article__old";
CREATE INDEX"blog_article_b583a629" ON "blog_article"("category_id");
--
-- Add field tags to article
--
CREATE TABLE "blog_article_tags"("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,"article_id" integer NOT NULL REFERENCES "blog_article"("id"), "tag_id" integer NOT NULL REFERENCES"blog_tag" ("id"));
CREATE UNIQUE INDEX"blog_article_tags_article_id_b78a22e9_uniq" ON "blog_article_tags"("article_id", "tag_id");
CREATE INDEX"blog_article_tags_a00c1b00" ON "blog_article_tags"("article_id");
CREATE INDEX"blog_article_tags_76f094bc" ON "blog_article_tags"("tag_id");
COMMIT;
最后应用migration
$ 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
我们需要一个管理员用户来管理网站上的内容:
$ python manage.py createsuperuser
Username: admin
Email address: [email protected]
Password: **********
Password (again): *********
Superuser created successfully.
之后我们重启服务器,在浏览器上输入http://127.0.0.1:8000/admin/
什么?没有看到自己写的模型?那是因为没有在admin.py上注册
/blog/admin.py
from django.contrib import admin
from .models import Article,Category,Tag
# Register your models here.
class ArticlePostAdmin(admin.ModelAdmin):
list_display = ('title','date','category') #list_display决定了视图的格式
#向管理界面注册模型
admin.site.register(Article,ArticlePostAdmin)
admin.site.register(Category)
admin.site.register(Tag)
保存刷新,就看到你自己写的模型了
模型已经建好了,接下来就是定义url、视图和模板了
我们先介绍一下url函数
url(regex,view,name,kwargs)
regex:正则表达式
view:地址满足该正则表达式时调用的视图函数
name(非必需):可以通过name来反向获取URL
kwargs(非必需): 一个字典类型的参数
我们先修改工程下的 /urls.py
/blogsite/urls.py
"""blogsite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
#include函数:包含 /blog/urls.py 文件的urlpatterns
url(r'^$',include('blog.urls')), #直接跳转至博客目录
url(r'^blog/',include('blog.urls')),
url(r'^admin/', admin.site.urls),
]
再前往/blog 目录下新建urls,py文件
/blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.index,name='index'), #/或/blog时调用views.index函数,加载主页
url(r'^(?P[0-9]+)/',views.article,name='article'), #/blog/数字:调用views.article函数,加载博文
url(r'^cat=(?P[0-9]+)',views.category,name = 'category') #/blog/cat=数字:调用views.category
]
之后编写views.py文件,实现刚才提到的函数
/blog/views.pyfrom django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.template import loader
from .models import Article,Category,Tag
# Create your views here.
def index(request):
latest_articles_list = Article.objects.order_by('-date') #将文章按照时间顺序生成列表
category_list = Category.objects.order_by('-name') #将分类按照名称顺序生成列表
template = loader.get_template('blogs/index.html') #获取模板html文件,该文件将在之后编写
context = {
'latest_articles_list' : latest_articles_list,
'category_list' : category_list,
} #传给模板html的后台数据
return render(request,'blogs/index.html',context)
def article(request,article_id):
try:
article = Article.objects.get(pk=article_id) #按编号查询文章
except Article.DoesNotExist: #如果找不到则抛出异常处理
raise Http404("Article does not exist")
return render(request, 'blogs/article.html', {'article': article})
def category(request,category_id):
cur_cat = Category.objects.get(pk = category_id)
articles = Article.objects.filter(category = cur_cat) #找到一个或多个该分类下的文章,因为可能是多个文章所以应该用filter函数
return render(request, 'blogs/category.html', {'articles': articles})
好了,现在我们要在/blog下创建一个templates文件夹,在templates文件夹下再建一个blogs文件夹用于存放模板html文件。
模板格式:
{% 表示逻辑的语句 %}
{{ 变量 }}
{# 注释 #}
创建3个模板html文件(随手写了3个用作示范,后期前端代码应该重写):
1、/blog/templates/blogs/index.html
{% if latest_articles_list %}
最近博文
{% for article in latest_articles_list %}
- {{article.title}}
{% endfor %}
{% else %}
No articles are avaliable
{% endif %}
{% if category_list %}
博文分类
{% for category in category_list %}
- {{category.name}}
{% endfor %}
{% endif %}
2、/blog/templates/blogs/category.html
{% if articles %}
{% for article in articles %}
- {{article.title}}
{% endfor %}
{% else %}
No articles are avaliable
{% endif %}
3、/blog/templates/blogs/article.html
{{article.title}}
{{article.date}}
{{article.body}}
{{article.category.name}}
最终效果如下:
http://blog.sina.com.cn/s/blog_875a5f5f0102woix.html
http://tenlee2012.github.io/2016/04/21/Django添加全文搜索功能入门/