Django practice - personal blog website

After watching Django video in a week, it took two days to finish it

Watching the progress of video learning is too fast, so flask and ajax are not very useful. Do a good job of this project and review it later. django is a kind of knowledge that can be consolidated immediately after learning. It's really convenient to do WEB projects
There are a lot of troubles in blogging, among which I don't know when to use ajax (this project doesn't use ajax),json transmission. If I am familiar with Ajax, I should do it faster

Blog functions:

1. * * write a blog * * (submit the form on the web page and save it in the database)

2. * * display blog list * * (if there is no error after writing the blog, go to the display interface and add a page,
Three blogs are displayed on each page. The body of the blog is limited to 100 words. You can click the blog title to enter the detailed interface of the blog.)

3. * blog detail page * (added the function of visitor comments and display comments on this page)

4. * * manage blog - modify / delete * * (click the corresponding button to enter the manage blog page, and the blog will be presented in the form of table 
You can choose to modify the blog or delete the blog)

5. Management comments - same function as above

6. On the blog display page, you can * * display the number of comments and the amount of reading * * under each blog (originally thought to be difficult, but it can be realized easily)

There are several other pages besides blogs

The front-end uses the other interfaces of template house for reference, which are introduced to myself and my school, and are made at will. No introduction

1. The construction of Django framework environment

To create a new Django project, I use Linux to create a new folder, Django, and open the terminal in this directory
Command line input

#myweb custom name
django-admin startproject myweb

cd myweb to create an application

python3 manage.py startapp index #index name at will

open this project in pycharm Enterprise Edition
First register index app in settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'index',
]

Do some preparatory work
Change the template in settings.py
Create a new folder templates

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],

Create a new folder static to store images css js files
Add staticfiles? Dirs at the bottom of settings.py=

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)

Change the language and time zone

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

data base

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', #If you don't use mysql, you need to change it 
        'NAME': 'myblog',#Database name enters mysql at the terminal to create a good database
        'USER':'root', 
        'PASSWORD':123456,
        'HOST':'localhost',
        'POST':3306,
        'OPTIONS': {  
      #  Because the project needs to use many to many mapping, there will be problems when deleting and modifying. Add this attribute to OK
            "init_command": "SET foreign_key_checks = 0;",
        }
    }
}

settings.py finished modifying Init.py under myweb
If you do not add this connection to the database, there will be an error

import pymysql
pymysql.install_as_MySQLdb()

Next, go to myweb - > urls.py

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^',include('index.urls')),
]

Create urls.py in the index folder

from django.conf.urls import url
from .views import *
urlpatterns =[
  url(r'^index/$',index),
]

Models creating data tables

In modell.py under index

  1. Blog s - blogs - blogs and categories are one to many blogs and tags are many to many
  2. Cataloy - Classification
  3. Tag - Tags
  4. Comment - comments and blogs are many to one

DB table is to modify the table name in the database, which is originally XXX blog plus DB table ='blog ', which is a real blog
verbose_name_plural = 'blog' is displayed as Chinese in the background of 127.0.0.1/admin or blogs

from django.db import models

# Create your models here.
class Catagory(models.Model):
    """
    //Blog classification
    """
    name = models.CharField('Name', max_length=30)
    def __str__(self):
        return self.name
    class Meta:
        db_table = 'catagroy'
        verbose_name_plural = 'Blog classification'
class Tag(models.Model):
    """
    //Blog Tags
    """
    name = models.CharField('Name', max_length=16)
    def __str__(self):
        return self.name
    class Meta:
        db_table = 'tag'
        verbose_name_plural = 'Blog Tags'
class Blog(models.Model):
    """
    //Blog
    """
    title = models.CharField('Title', max_length=32)
    author = models.CharField('author', max_length=16)
    content = models.TextField('Blog text')
    created = models.DateTimeField('Release time', auto_now_add=True)
    catagory = models.ForeignKey(Catagory, verbose_name='classification')
    tags = models.ManyToManyField(Tag, verbose_name='Label')
    commentNum = models.IntegerField('Comment quantity',default=0)
    readnum = models.IntegerField('Reading volume',default=0)
    def __str__(self):
        return self.title
    class Meta:
        db_table = 'blog'
        verbose_name_plural = 'Blog'
class Comment(models.Model):
    """
    //comment
    """
    blog = models.ForeignKey(Blog, verbose_name='Blog')
    name = models.CharField('call', max_length=16)
    email = models.EmailField('mailbox')
    content = models.CharField('content', max_length=240)
    created = models.DateTimeField('Release time', auto_now_add=True)
    def __str__(self):
        return self.content
    class Meta:
        db_table = 'comment'
        verbose_name_plural = 'comment'

Remember to execute after creating the table

python3 manage.py makemigrations
python3 manage.py migrate

Register the data table in admin.py under index, which can be managed in the background

from django.contrib import admin

from .models import *
# Register your models here.
admin.site.register(Catagory)
admin.site.register(Comment)
admin.site.register(Tag)
admin.site.register(Blog)

Create a super user, input the account and password in turn, create a mailbox, and then run the service

python3 manage.py createsuperuser

If it's OK, run and try

python3 manage.py runserver

Enter 127.0.0.1/admin on the web page to enter the background management database

Import the front-end page into templates static in the framework

Some pictures and hyperlinks have to be addressed correctly


I've been preparing for half the day.. The next part is about how to realize the function of blog

5 original articles published, 25 praised, 1453 visited
Private letter follow

Tags: Django Database MySQL JSON

Posted on Thu, 16 Jan 2020 06:07:01 -0800 by darence