Python uses Django to develop its own blog system

高洛峰
Release: 2017-02-25 11:17:14
Original
2101 people have browsed it

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>XX博文</h1>
<h3>小生不才,但求简约!</h3>
{% block content %}
{% endblock %}
</body>
</html>
Copy after login

•然后就是子模板BlogTemplate.html

{% extends "base.html" %}
 {% block content %}
  {% for post in blog_list %}
   <h2>{{ 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中文网!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template