Django2. X build blog


Statement: the following is my personal understanding. If you find any mistakes or questions, you can contact me for discussion

brief introduction

After learning django2. X, you can build a personal blog to practice hands


Create project

Creating blog project and virtual environment through pychar

Django2. X build blog

Modify related settings

Allow any domain name

When developing and testing, you can fill in here as *, and modify it to the specified domain name after the later deployment goes online


Register apps


Configuration template


After registration, create the Templates folder in the root directory of the project (that is, the directory where manage. Py is located). Creating a project with pychar will automatically help us create it

Configuration database


Creating MySQL database

After registering the database, create the MySQL database

>>> mysql -uroot -p
mysql> create database djangoblog charset=utf8;
mysql> show databases;
| Database           |
| information_schema |
| blog               | 
| djangoblog         |
| mysql              |
| performance_schema |
| sys                |
6 rows in set (0.01 sec)

Database migration

Next, migrate the database and create Django admin administrator

According to the previous article:Configure MySQL correctly with django2.0, configure MySQL database

Next, database migration

(DjangoBlogEnv) hls-MacBook-Pro:DjangoBlog hl$ python makemigrations
 No changes detected
 (DjangoBlogEnv) hls-MacBook-Pro:DjangoBlog hl$ python migrate
 Operations to perform:
   Apply all migrations: admin, auth, contenttypes, sessions
 Running migrations:
   Applying contenttypes.0001_initial... OK
   Applying auth.0001_initial... OK
   Applying admin.0001_initial... OK
   Applying admin.0002_logentry_remove_auto_add... OK
   Applying admin.0003_logentry_add_action_flag_choices... 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 auth.0008_alter_user_username_max_length... OK
   Applying auth.0009_alter_user_last_name_max_length... OK
   Applying auth.0010_alter_group_name_max_length... OK
   Applying auth.0011_update_proxy_permissions... OK
   Applying sessions.0001_initial... OK

Applying sessions.0001 appears_ Initial… OK means that the MySQL database has been configured. Next, create a Django admin administrator

(DjangoBlogEnv) hls-MacBook-Pro:DjangoBlog hl$ python createsuperuser

At this stage, the database configuration has been completed. The databases generated here are some of Django’s own libraries

Other settings

  • Regional language settings, to prevent the admin interface garbled

    #Set language to Chinese
  • Static folder and multimedia folder setting

    #Set static file directory and name

    After setting in, we also create these two files in the project, and create static and media folders in the root directory of the project

Configure pychar running parameters

Django2. X build blog

Django2. X build blog

After the configuration is completed, click the run button in pychar and enter in the browser to access it. When the small rocket is launched, it means that Django is installed successfully. Visit Django admin interface and enter in the browser127.0.0.1:8000/adminTo see Django management, you need to enter the user name and password. After entering the user name and password, you can jump to the Django management page, indicating that Django admin is set successfully

Database table analysis

Article table

field type remarks
id PrimaryKey Primary key
title CharField title
create_time DateTimeField Creation time
views PositiveIntegerField Number of readings
summary TextField abstract
content TextField content
category_id ForeignKey Foreign key, category ID
tag_id ManyToManyField Foreign key, tag ID

Classification table

field type remarks
id PrimaryKey Primary key
name CharField Category name

Label table

field type remarks
id PrimaryKey Primary key
name CharField Tag name

User table

field type remarks
id PrimaryKey Primary key
name CharField user name
password CharField password

Comment sheet

field type remarks
id PrimaryKey Primary key
user_id ManyToManyField Foreign key, user ID
blog_id ManyToManyField Foreign key, blog ID
create_time DateTimeField Creation time
content TextField Comment content
Parent_id PositiveIntegerField Parent comment ID

Write model class code

Complete the model class code according to the database design table

# DjangoBlog/post/

Database migration

(DjangoBlogEnv) hls-MacBook-Pro:DjangoBlog hl$ python makemigrations
Migrations for 'blog':
    - Create model Article
    - Create model Category
    - Create model Tags
    - Create model User
    - Create model Comment
    - Add field category_id to article
    - Add field tag_id to article
(DjangoBlogEnv) hls-MacBook-Pro:DjangoBlog hl$ python migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying blog.0001_initial... OK

Managing with Django admin

After the completion of database migration, a migrated file will be generated in the post application, and then the model will be registered in Django admin, which is convenient for us to manage with Django admin


Log in to Django management background, check whether the model can be managed, and try to click Add and modify. If there is no problem, the registration is successful

Integrating markdown

Many people like to blog in markdown format. We can achieve this function by integrating Django mdeditor

1. Install Django mdeditor

pip install django-mdeditor

2. Register in apps


3. Create the editor folder under media

cd media
mkdir editor

4. Integrate into routing


from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
url(r'mdeditor/', include('mdeditor.urls'))

if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Integrate into models

from mdeditor.fields import MDTextField
class Article(models.Model):
    content = MDTextField()

Enter admin again, select the article to modify, and you can see the integrated markdown editor

Implementation view

First, find a template you like, download the template, put the HTML part into templates, and put other static files into static

The repeated parts are extracted according to their own template, each of which is different, and the static file is loaded

If it is not extracted well at one time, it can be extracted slowly. For a back-end programmer, this is a process of slow work and meticulous work. You can write a simple view and then open Django to extract and debug it

Next, try to realize the home page

First, configure the route in URLs. Py

from blog import views

urlpatterns = [
  path('', views.index, name='index')

Here, the first parameter in the path is the URL of the access, the regular expression is used for matching, the second parameter is the view function, and the third parameter is the name

Next, write the view function in views. Py of the blog application

def index(request):
    return render(request, 'index.html')

So when we revisit, our modified front-end code will be loaded

Next, we implement the classification loading and modify the index view to the following code


In the front-end code rendering, we find base. HTML and change the code in UL tag except for the home page to the following code

<header class="header-navigation" id="header">

In this way, the classification column is loaded. If there is no data, you can add data through admin

This work adoptsCC agreementReprint must indicate the author and the link of this article