Python starts from scratch -- the official blog project starts from 0

1, Create database model

1. The basic principles are as follows:

	Each model exists in Django as a Python class
	Each model is a subclass of django.db.models.Model
	Each class in the model represents a table in the database
	Each field (property) of the model represents a column of the data table
	Django will automatically generate database access API for you
	For blog project data types, we need to store six kinds of data: article classification, article, article label, slide chart, recommendation position, and friendship link. One table for each type of data

2. Blog model code

Open blog/ and enter the code:

from django.db import models
from django.contrib.auth.models import User

# Import Django's own user module

# Article classification
class Category(models.Model):
    name = models.CharField('Blog classification', max_length=100)
    index = models.IntegerField(default=999, verbose_name='Sorting and sorting')

    class Meta:
        verbose_name = 'Blog classification'
        verbose_name_plural = verbose_name

    def __str__(self):

# Article Tags
class Tag(models.Model):
    name = models.CharField('Article Tags', max_length=100)

    class Meta:
        verbose_name = 'Article Tags'
        verbose_name_plural = verbose_name

    def __str__(self):

# Recommended bit
class Tui(models.Model):
    name = models.CharField('Recommended bit', max_length=100)

    class Meta:
        verbose_name = 'Recommended bit'
        verbose_name_plural = verbose_name

    def __str__(self):

# Article
class Article(models.Model):
    title = models.CharField('Title', max_length=70)
    excerpt = models.TextField('abstract', max_length=200, blank=True)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, verbose_name='classification', blank=True, null=True)
    # Using foreign key to associate classification table with classification is one to many relationship
    tags = models.ManyToManyField(Tag, verbose_name='Label', blank=True)
    # Using foreign key to associate label table with label is many to many relationship
    img = models.ImageField(upload_to='article_img/%Y/%m/%d/', verbose_name='Article pictures', blank=True, null=True)
    body = models.TextField()

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='author')
    //Author of the article, here User is imported from django.contrib.auth.models.
    //Here we associate the article with User through ForeignKey.
    views = models.PositiveIntegerField('Reading volume', default=0)
    tui = models.ForeignKey(Tui, on_delete=models.DO_NOTHING, verbose_name='Recommended bit', blank=True, null=True)

    created_time = models.DateTimeField('Release time', auto_now_add=True)
    modified_time = models.DateTimeField('Modification time', auto_now=True)

    class Meta:
        verbose_name = 'Article'
        verbose_name_plural = 'Article'

    def __str__(self):
        return self.title

# Banner
class Banner(models.Model):
    text_info = models.CharField('Title', max_length=50, default='')
    img = models.ImageField('Rotation chart', upload_to='banner/')
    link_url = models.URLField('pictures linking', max_length=100)
    is_active = models.BooleanField('Whether it is active', default=False)

    def __str__(self):
        return self.text_info

    class Meta:
        verbose_name = 'Rotation chart'
        verbose_name_plural = 'Rotation chart'

# Friendship links
class Link(models.Model):
    name = models.CharField('Link name', max_length=20)
    linkurl = models.URLField('Website', max_length=100)

    def __str__(self):

    class Meta:
        verbose_name = 'Friendship links'
        verbose_name_plural = 'Friendship links'

We have added an img image cover field to upload the article cover image. article_img / is the upload directory, and Y/%m/%d / is to automatically add the file upload time to the uploaded image.

Before migration, we need to set the database first. If we use the default database, we don't need to set it. Django uses it by default

sqlite3 database, if we want to use Mysql database, we need to configure it separately. We open the file, find DATABASES, and modify it to the following code:

#Modify it to mysql as follows:
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',    #Your database name
        'USER': 'root',   #Your database user name
        'PASSWORD': '445813', #Your database password
        'HOST': '', #Your database host, leave blank and the default is localhost
        'PORT': '3306', #Your database port

#Since mysql default engine is mysql dB, add the following code to the "init. Py" file under myblog

import pymysql
pymysql.version_info = (1, 4, 6, 'final', 0)  # change mysqlclient version,because python version is 3.7 and pymysql version is 0.93
#If the pymysql module cannot be found, install it through pip install pymysql.

3. After the database is set up, we will successively enter the following commands to migrate the database:

	python makemigrations
	python migrate

When migrating, you will be prompted as follows:

The reason for this is that our slide show uses the image field, so we need to introduce the image processing package. The prompt also gives us the processing scheme. Enter the following command to install the pilot module:
pip install Pillow
Migrate database after successful installation

After the database migration is successful, the program will automatically generate several files with the beginning of 000 in the migrations directory under the blog, in which the database migration records are recorded

2, Manage background management data with Admin

Click Database in the top right corner of pysharm, and then select our Database file db.sqlite3 in the website project, and drag it to the Database box.

But there is no data. Refresh will report an error.

Pycham batabase is very limited. Let's show you how to use Django's own admin to manage website data. Django's admin background management allows us to manage data quickly and conveniently. We can control it in the file under each app directory.

To manage APP applications, the most basic premise is to register them in settings first, that is, add the APP name in installed Apus, which we mentioned in the previous article.

After registering the APP, we want to operate the database table in the admin background. We also need to register the database table in the file under the APP. Our APP application is blog, so we need to register in the blog/ file:

from django.contrib import admin
# Register your models here.
from .models import Banner, Category, Tag, Tui, Article, Link

#Import database tables to be managed

class ArticleAdmin(admin.ModelAdmin):
    list_display = ('id', 'category', 'title', 'tui', 'user', 'views', 'created_time')
    # Display the fields to be displayed in the article list
    list_per_page = 50
    # Automatic pagination for 50 pieces of data
    ordering = ('created_time',)
    #Sorting method of background data list
    list_display_links = ('id', 'title')
    # Set which fields can be clicked to enter the editing interface

class BannerAdmin(admin.ModelAdmin):
    list_display = ('id', 'text_info', 'img', 'link_url', 'is_active')

class CategoryAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'index')

class TagAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')

class TuiAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')

class LinkAdmin(admin.ModelAdmin):
    list_display = ('id', 'name','linkurl')

Log in to the management background

Background after registration:

There are more tables that we created in models. We can add, delete and modify these tables in the background.

3, Add data using rich text editor

When adding data in Django admin background, the text box of article content needs to write Html code if it wants to publish an article with both pictures and texts, which is very laborious and unable to upload pictures and files.

  1. First we download the DjangoUeditor package. Click the link below to download! Download and unzip to the project root.
  2. Register the APP in, and add 'DjangoUeditor', 'in the installed APUs.
    'DjangoUeditor', #Register rich text editor APP
  1. Add url to myblog/
from django.urls import path, include
#Notice that there is one more include in the above line

urlpatterns = [
    path('ueditor/', include('DjangoUeditor.urls')), #Add the URL of DjangoUeditor
  1. Modify the fields in blog/ that need to be rendered with a rich text editor. In this case, we need to modify the body field in the Article table.

Put the original: blog/

body = models.TextField()

Change to: blog/

from DjangoUeditor.models import UEditorField #Add this line of code in the header to import UEditorField

body = UEditorField('content', width=800, height=500, 
                    toolbars="full", imagePath="upimg/", filePath="upfile/",
                    upload_settings={"imageMaxSize": 1204000},
                    settings={}, command=None, blank=True

Pay attention to the two paths of imagePath = "upimg /", filePath = "upfile /", which are the path of image and file upload. When we upload a file, it will be automatically uploaded to the corresponding upimg and upfile directories under the media folder of the project root directory. The directory name can be defined by yourself. Some people ask, why is it uploaded to the media directory? That's because we set the upload file directory media in the basic configuration article.

After the above steps are completed, we start the project and enter the article publishing page. Prompt error:

render() got an unexpected keyword argument 'renderer'

The error picture is as follows:

There is a prompt on the error page. The error is in line 96 of the following file. Open 93 lines of this file, and comment this line.

After the modification, refresh the page again, and you can see that our rich text editor displays normally.

Note that if we upload images in the rich text editor, the uploaded images will not be displayed in the content of the editor. Then we need to make the following settings, open the myblog/ file, and enter the following code in it:


from django.urls import path, include, re_path
#Add an extra re? Path to the above line
from django.views.static import serve
#Import static file module
from django.conf import settings
#Import the file upload configuration in the configuration file

urlpatterns = [
    re_path('^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),#Increase this trip

After setting, the picture will display normally. In this way, we can use the DjangoUeditor rich text editor to publish articles with both pictures and texts.

Published 3 original articles, won praise 0, visited 2798
Private letter follow

Tags: Database Django MySQL Python

Posted on Sun, 15 Mar 2020 05:52:00 -0400 by swordske