Python uses Django to implement the full version of the blog system, pythondjango
Today, I spent some time building a blog system. Although it is not related to interface beautification, it is okay to publish it.
Development Environment
Operating System: windows 7 64-bit
Django: 1.96
Python: 2.7.11
Ides: PyCharm 2016.1
Function
Since it is a blog system, it is naturally a blog. Let's think about the attributes of a blog. Therefore, we need to be able to add, delete, modify, comment, tag, and classify a blog.
Link Analysis
Attribute
Blog: title, content.
Tag: Tag Name
Category: category name
Comment: reviewer, reviewer email, comment content
Link
Blog: A blog can contain multiple tags, multiple comments, and belong to one category.
Tags: a type of tag can be assigned to Multiple blogs. A blog can also contain multiple tags, so it is a multi-to-many relationship.
Category: A category can contain multiple blogs, so it has a one-to-many relationship with blogs.
Comment: Obviously, a comment belongs to a blog, and a blog can have many comments, so it is a one-to-many relationship.
Model Layer Design
If you don't need to talk about it, simply design it based on the Link Analysis in the previous step.
# Coding: utf8from _ future _ import unicode_literalsfrom django. db import models # Create your models here. class Catagory (models. model): "blog category" "name = models. charField ('name', max_length = 30) def _ unicode _ (self): return self. nameclass Tag (models. model): "blog tag" name = models. charField ('name', max_length = 16) def _ unicode _ (self): return self. nameclass Blog (models. model): "blog" title = models. charField ('title', max_length = 32) author = models. charField ('author ', max_length = 16) content = models. textField ('blog body') created = models. dateTimeField ('release time', auto_now_add = True) catagory = models. foreignKey (Catagory, verbose_name = 'category') tags = models. manyToManyField (Tag, verbose_name = 'tag') def _ unicode _ (self): return self. titleclass Comment (models. model): "comment" "blog = models. foreignKey (Blog, verbose_name = 'blog ') name = models. charField ('name', max_length = 16) email = models. emailField ('mailbox ') content = models. charField ('content', max_length = 240) created = models. dateTimeField ('release time', auto_now_add = True) def _ unicode _ (self): return self. content
Database settings
# Database# https://docs.djangoproject.com/en/1.9/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}
Then Django can reverse generate the underlying business logic of the Database Based on our model. Then you need to call the relevant commands.
python manage.py makemigrationspython manage.py migrate
In this way, the framework will help us complete the underlying database operations. Do not worry about the relationship between tables.
Management Layer
Since we have created a model, we take it for granted that we need to manage it. Let's make the admin debut, so we need to register the model to the admin, these three options will appear on the Management page.
Controller Layer Design
In fact, it is the writing of urls. py. There is nothing to say, as shown below:
# Coding: utf8from django. contrib import admin # Register your models here. from Blog. models import * # The purpose of registration is to allow the system administrator to manage the registered models admin. site. register ([Catagory, Tag, Blog])
The following describes the details of urls. py.
"""MyDjango2 URL ConfigurationThe `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 urlfrom django.contrib import adminfrom Blog.views import *urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blogs/$',get_blogs), url(r'^detail/(\d+)/$',get_details ,name='blog_get_detail'),]
View Layer
The view layer is shown as follows:
from django.shortcuts import render,render_to_response# Create your views here.from Blog.models import *from Blog.forms import CommentFormfrom django.http import Http404def get_blogs(request): blogs = Blog.objects.all().order_by('-created') return render_to_response('blog-list.html',{'blogs':blogs})def get_details(request,blog_id): try: blog = Blog.objects.get(id=blog_id) except Blog.DoesNotExist: raise Http404 if request.method == 'GET': form = CommentForm() else: form = CommentForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data cleaned_data['blog'] = blog Comment.objects.create(**cleaned_data) ctx = { 'blog':blog, 'comments':blog.comment_set.all().order_by('-created'), 'form':form } return render(request,'blog_details.html',ctx)
You may also see the template html, so next we will introduce the template writing.
Template System
Here, two templates are used: one is the blog list template and the other is the blog details Interface Template. With the template variables and template labels, this is what it looks like.
See blog_list.html first
<! DOCTYPE html>
Add Comment
The Django forms module can be used to easily integrate the comment function.
We need to create a new form. py in the Blog application for processing.
# Coding: utf-8from django import forms "to achieve blog comment function" class CommentForm (forms. Form): "comment Form used to post blog comments. The class of the Comment Form defines three fields as required: name, email address, and comment content. In this way, we can use it to quickly generate forms and verify user input. "Name = forms. charField (label = 'name', max_length = 16, error_messages = {'required': 'enter your name', 'max _ length ': 'Name Too Long'}) email = forms. emailField (label = 'mailbox ', error_messages = {'requestred': 'enter your mailbox', 'invalid': 'incorrect email format '}) content = forms. charField (label = 'comment content', error_messages = {'requestred': 'enter your comment! ', 'Max _ length': 'comment too long '})
This file can be reflected in the ctxin views.pyand in the blog_details.html template file.
Start the service
Python manage. py runserver
Call this function to start our development server. Then input http: // 127.0.0.1: 8000/blogs in the browser and you will find the following interface.
Click one to go to the blog details page.
Because the interface is ugly, we will not demonstrate it here, but it is indeed very powerful, especially for the comment verification function.
Summary
The "cool" Blog system has not been completed yet. It will be better to add some CSS special effects. If you integrate the rich media editor, the effect will be better.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.