Table of Contents
XX博文
小生不才,但求简约!
{{ post.title }}
Home Backend Development Python Tutorial Python uses Django to develop its own blog system

Python uses Django to develop its own blog system

Feb 25, 2017 am 11:17 AM
django python Blog system

I have wanted to build my own blog system for a long time, but after searching on the Internet, it seems that it requires some knowledge about Node.js and installing so many libraries and so on, so I don’t want to touch it. But I encountered such an artifact like Django, and I didn't expect that my blog system would be established like this. Although it is the most basic type. But it can be considered a success. This blog is more suitable for children who have a certain understanding of Django. If you are a novice, it is recommended to take a look at the basic knowledge points of Django before doing experiments, which will be more efficient!

Okay, without further ado, let’s get started.

Building a framework
•Creating projects and applications

Building a framework means installing Django and doing Good relevant configuration. Because I created it under PyCharm, the tools did a lot of things for me. But the bottom layer is nothing more than the following lines of code:

Create a Django project named MyDjango

##django-admin startproject MyDjango

Create a Django application named MyBlog. It should be noted here that the application belongs to a subset of the project. In layman's terms, application folders exist as a subset of project folders.

django-admin startapp MyBlog

•Create database and underlying model

I simply use the default sqlite3 database as the database of my blog system. Of course, you can also customize the database you need. Generally speaking, sqlite3 can meet the needs. You can set it up like this in setting.py.


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
 'default': {
  'ENGINE': 'django.db.backends.sqlite3',
  'NAME': 'MyBlog.db',
  'USER':'',
  'PASSWORD':'',
  'HOST':'',
  'PORT':'',
 }
}
Copy after login

After the database is built, the next step is to create the model. Because I am creating a blog system, it is essential to publish content about the blog, so I need to have attributes such as title, content, and publishing time. Details such as models.py file

from __future__ import unicode_literals
from django.contrib import admin
from django.db import models


# create the blog model

class BlogPost(models.Model):
 title = models.CharField(max_length=150)
 body = models.TextField()
 timestamp = models.DateTimeField()

 def __unicode__(self):
  return self.title
Copy after login


Since administrators are required to manage published blogs, we need to set up a management model for published blogs,


# set the admin page for BlogPost

class BlogPostAdmin(admin.ModelAdmin):
 list_display = ('title','timestamp')


# register the model (especially important

admin.site.register(BlogPost)
Copy after login


So the entire models.py file should look like this.

from __future__ import unicode_literals
from django.contrib import admin
from django.db import models


# create the blog model

class BlogPost(models.Model):
 title = models.CharField(max_length=150)
 body = models.TextField()
 timestamp = models.DateTimeField()

 def __unicode__(self):
  return self.title



# set the admin page for BlogPost

class BlogPostAdmin(admin.ModelAdmin):
 list_display = ('title','timestamp')


# register the model (especially important

admin.site.register(BlogPost)
Copy after login

The next step is to synchronize the connection between the database and the model. If you do not perform synchronization operations, it is very likely to report

django.db.utils.OperationalError: unable to open database file
And this is also a very important link. That's the problem with the Django version. I've run into this before.

django < 1.7: python manage.py syncdb

##django > 1.7: python manage.py makemigrations python manage.py migrate

Improving the MVC model

In fact, in terms of the previous steps, We have completed the functions of the model module, and the next step is to map the views.


•V (views.py) view layerWe need to define the underlying logic processing in this file. This determines what kind of response is returned to the user. As for which rendering method to use, don’t waste unnecessary time on it. render_to_response is enough.


# create the view for blog show

def myBlogs(request):
 blog_list = BlogPost.objects.all()
 return render_to_response(&#39;BlogTemplate.html&#39;,{&#39;blog_list&#39;:blog_list})
Copy after login

The template file is used here, and a list type parameter is also passed to the template. We will discuss these later.

•C(controller)urls.pyIt can be said that this file connects the loosely coupled functions of various parts of Django together, and it is completed The non-core core of the operation of the entire project is the processing of mapping logic. Next we will set up our blog system.

from django.conf.urls import url
from django.contrib import admin
from MyBlog.views import *

urlpatterns = [
 url(r&#39;^admin/&#39;, admin.site.urls),
 url(r&#39;^myBlogs/$&#39;,myBlogs),
]
Copy after login

Regarding how to map, my last article has a detailed introduction, PyCharm develops Django basic configuration. Those who are interested can refer to it. Okay, this time after we complete the settings of the admin administrator user, we can run our program.

python manage.py runserver

Appears:

Performing system checks...

System check identified no issues (0 silenced).
June 05, 2016 - 11:39:27
Django version 1.9.6, using settings &#39;MyDjango.settings&#39;
Starting development server at http://www.php.cn/:8000/
Quit the server with CTRL-BREAK.
Copy after login

You can then enter ## in the browser #http://127.0.0.1:8000/admin. After successfully logging in, you can click Blog Posts below to edit blog posts. Then click the SAVE button to publish our blog. Next, enter

http://127.0.0.1:8000/myBlogs/ in the browser to access our blog system.


This completes the establishment of our blog system. But since no styles are added, it doesn’t look very good, so we are going to add the following template styles.

Template configuration

接着刚才的继续,关于模板,这里面可谓是有着很深的设计哲学。了解过的大家肯定都会有感触,我就不多说了。
接下来就为我们的博客系统设置一下模板吧。
•父模板base.html
按照django对模板的继承设置,我们可以制作一个父模板。如下:

<!DOCTYPE html>
<html lang="zh">
<head>
 <meta charset="UTF-8">
 <title>标题</title>
</head>
<style type="text/css">
 body{
  color: #efd;
  background: #BBBBBB;
  padding: 12px 5em;
  margin:7px;
 }
 h1{
  padding: 2em;
  background: #675;
 }
 h2{
  color: #85F2F2;
  border-top: 1px dotted #fff;
  margin-top:2em;
 }
 p{
  margin:1em 0;
 }
</style>
<body>
<h1 id="XX博文">XX博文</h1>
<h3 id="小生不才-但求简约">小生不才,但求简约!</h3>
{% block content %}
{% endblock %}
</body>
</html>
Copy after login

•然后就是子模板BlogTemplate.html

{% extends "base.html" %}
 {% block content %}
  {% for post in blog_list %}
   <h2 id="nbsp-post-title-nbsp">{{ post.title }}</h2>
   <p>{{ post.timestamp }}</p>
   <p>{{ post.body }}</p>
  {% endfor %}
 {% endblock %}
Copy after login

需要注意的就是模板中的模板标签以及模板变量都应该与views.py文件对应的函数中的字典变量相一致,否则django虽然不会报错,但也是不会显示数据的。 

接下来刷新一下,输入http://127.0.0.1:8000/admin/

点击add按钮,开始添加你的博文吧。

Python uses Django to develop its own blog system

Python uses Django to develop its own blog system

然后在浏览器中输入
http://www.php.cn/:8000/myBlogs/.你就可以看到你的博客列表了,如图

Python uses Django to develop its own blog system

大家可能已经看到了,问题就出在点击标题没有进入到相关的详情页面,那是因为还没有添加这个功能呢。(^__^) 嘻嘻……

总结

今天一起做了一个简单的博客系统,虽然外观看起来并不是很好看,但是内容什么的差不多就是这样了。还有很多的地方需要完善。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多Python uses Django to develop its own blog system相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Can Python parameter annotations use strings? Can Python parameter annotations use strings? Apr 01, 2025 pm 08:39 PM

Alternative usage of Python parameter annotations In Python programming, parameter annotations are a very useful function that can help developers better understand and use functions...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

How do Python scripts clear output to cursor position at a specific location? How do Python scripts clear output to cursor position at a specific location? Apr 01, 2025 pm 11:30 PM

How do Python scripts clear output to cursor position at a specific location? When writing Python scripts, it is common to clear the previous output to the cursor position...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

How to use Python and OCR technology to try to crack complex verification codes? How to use Python and OCR technology to try to crack complex verification codes? Apr 01, 2025 pm 10:18 PM

Exploration of cracking verification codes using Python In daily network interactions, verification codes are a common security mechanism to prevent malicious manipulation of automated programs...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles