First, preparatory workWith Python and Django installed, I'm using Python 2.7.11 and Django 1.9.8.
After installation, you can start.
Open a new project
$ django-admin startproject blogsite (website project name)
Build the project folder after success, structured as follows
Blogsite/
manage.py
Blogsite/
__init__.py
settings.py
urls.py
wsgi.py
Run the server at this time
$ python manage.py runserver
See the following information on the console
Performing system checks ...
System Check identified no issues (0silenced).
You have unapplied migrations; Your app maynot work properly until they.
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.
Open the browser at this time, enter Http://127.0.0.1:8000/, you will see this information
You can also modify the/blogsite/setting.py to change the language and time zone
Language_code = ' Zh-hans '
Time_zone = ' Asia/shanghai '
Run the server again, refresh the page
And then we create an app
$ python manage.py Startapp Blog
A folder blog is created with its internal structure as follows
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
Register app
/blogsite/setting.py
# application definition
Installed_apps = [
' Blog.apps.BlogConfig ',
...
]
......
Second, the construction of the model
Blogs need those models.
Blog posts, blog categories, tags
According to the class you designed to modify
/blog/models.py
#-*-coding:utf-8-*-from __future__ import unicode_literals to django.db import models from Dja
ngo.utils.encoding Import python_2_unicode_compatible # Create your models here. @python_2_unicode_compatible #如果要求python2支持utf-8 You need to add this sentence class Category (models). Model): name = models.
Charfield (U ' name ', max_length = ~) def __str__ (self): return self.name; @python_2_unicode_compatible class Tag (models. Model): name = models.
Charfield (U ' name ', max_length = ~) def __str__ (self): return self.name; @python_2_unicode_compatible class Article (models. Model): title = models. Charfield (U ' title ', Max_length =) BODY = models. TextField (U ' body ') date = models. Datetimefield (U ' release time ') Category = models. ForeignKey (Category, verbose_name=u ' category ') tags = models. Manytomanyfield (tag, verbose_name = U ' label ', Blank=true) # models. ForeignKey says a article has a category # models. Manytomanyfield indicates that a article has multiple tag,blank=true representations that can be null def __str__ (self): return self.title
When you're done, register with the database, and here we'll use Python's own sqlite
First create a migration $ python manage.py makemigrations Blog
The console appears as follows and creates a python file named 0001_initial.py
0001_initial.py:
-Create Model Article
-Create Model Category
-Create Model Tag
-Add field category to article
-ADD field tags to article
Then write to the database
$ python manage.py sqlmigrate blog 0001
The console appears as follows:
BEGIN;
--
--Create Model Article
--
CREATE TABLE "Blog_article" ("id" integer NOT null PRIMARY KEY AutoIncrement, "title" varchar (+) 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 NOT NULL);
--
--Create Model Tag
--
CREATE TABLE "Blog_tag" ("id" integer NOT null PRIMARY KEY autoincrement, ' name ' varchar 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 (+) 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 ' BL Og_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;
Finally applied migration
$ python manage.py Migrate
The console appears as follows:
Operations to perform:
Apply all migrations:admin, blogs, 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
We need an admin user to manage the content on the site:
$ python manage.py createsuperuser
Username:admin
Email address:admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.
Then we reboot the server and enter http://127.0.0.1:8000/admin/on the browser.
Enter the username and password of the admin account before you log in and see the following after landing
What the. Did you not see the model you wrote? That's because it's not registered on the 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)
Save the refresh and see the model you wrote yourself.
Three, URLs, views, and templates
The model has been built, and the next step is to define URLs, views, and templates.
Let's introduce the URL function first.
URL (Regex,view,name,kwargs)
Regex: Regular Expression
View: An address is called when the regular expression is met
Name (not required): The URL can be retrieved in reverse by name
Kwargs (not required): A parameter of a dictionary type
We first revise the/urls.py under the project.
/blogsite/urls.py
"" "Blogsite URL Configuration the
' urlpatterns ' list routes URLs to views. For more information please:
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: URLs (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
1. Import the Include () function:from django.conf.urls import URL, include
2. Add a URL to urlpatterns: url (r ' ^blog/', include (' Blog.urls ')) "" "" ",
Include
from django.contrib import admin
urlpatterns = [
#include函数: Urlpatterns containing/blog/urls.py files
URL (r ' ^$ ', include (' Blog.urls '), #直接跳转至博客目录
url (r ' ^blog/', include (' Blog.urls ')),
url (r ' ^ Admin/', admin.site.urls),
]
And then go to the/blog directory to create a new urls,py file
/blog/urls.py
From Django.conf.urls import URLs
from. Import views
urlpatterns = [
url (R ' ^$ ', views.index,name= ' index ') Call the Views.index function when c3/>#/or/blog, loading the home page
url (r ' ^) (? p<article_id>[0-9]+)/', views.article,name= ' article '), #/blog/number: Call views.article function, load blog
url (r ' ^ Cat= (? p<category_id>[0-9]+) ', views.category,name = ' category ') #/blog/cat= number: calling Views.category
]
Then write the views.py file to implement the function mentioned earlier/blog/views.py
From django.core.urlresolvers import reverse to django.http import Http404, Httpresponseredirect, HttpResponse from Dja Ngo.shortcuts import Render, get_object_or_404 from django.template import loader import models
G # 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文件, The file will then write the context = {' latest_articles_list ': latest_articles_list, ' category_list ': category_list,} #传给模板html的后台 Data 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.obje Cts.get (pk = Category_id) articles = Article.objects.filter (category = Cur_cat) #找到一个或多个该分类下的文章, because it may be multiple articles, you should return to render with the filter function (
Request, ' blogs/category.html ', {' articles ': articles})
OK, now we're going to create a templates folder under/blog, and then build a blogs folder under the Templates folder to store the template HTML file.
Template format:
{% =% logical statement%}
{{variable}}
{# comment #}
Create 3 template HTML files (3 are written as demonstrations and late front-end code should be rewritten):
1,/blog/templates/blogs/index.html
{% if latest_articles_list%}
2,/blog/templates/blogs/category.html
{% If articles%}
<ul>
{% for article in articles%}
<li><a href= '/blog/{{article.id}}/' >{{article.title}} </a></li>
{% endfor%}
</ul>
{% Else%}
<p>no articles are avaliable</p >
{% endif%}
3,/blog/templates/blogs/article.html
The final effect is as follows:
Four, other to this a basic blog frame is put up, we can add some other features. When I wrote this framework, I made reference to these great God blogs. 1. Add Django Comment System http://answ.me/post/comment-in-django-part-1/
2. Add Rich Text editor CKEditor http://python-ning.github.io/2016/04/12/python_django_blog_ckeditor/
3, add search function: Haystack+whoosh+jieba
Http://blog.sina.com.cn/s/blog_875a5f5f0102woix.html Http://tenlee2012.github.io/2016/04/21/Django Add full-Text search feature /
4, share the function I use is Baidu one key sharing API.
The framework of the source code in this: Simple-django-blog need to improve the place please enlighten us.