❤️ Nanny level tutorial takes you to make your own blog website ❤️ [pure python implementation & & with source code]

Function introduction:

Homepage index.htmlShow the text of adding blog and blog list to realize page Jump
Add page add.htmlEnter the title and content of the article and submit the content to the database
List page list.htmlShow all blogs in the database to the front page. Click the article to view the details of the article, with editing and deletion functions
Details page detail.htmlDisplays the title and content of the article

👉🚔 Jump straight to the end 🚔 👈 ——> Get project source code~ 💖

1. Environment configuration and Django initialization

(1) Create a new virtual environment in ubuntu for the project:

Create a new virtual environment (named dja_env) for this project in ubuntu, and install the pymysql package for the project to operate the mysql database.

(2) Create a new empty Django project in pycharm:

  1. Create an empty Django project named blog in pycharm;
  2. Configure the connection with the remote project environment;

  1. And create a new blog_server APP;

(3) Perform database configuration and some minor configurations:

(operate the settings.py file in the project directory)

① Set allow everyone access


② Register new APP


③ Configure connection to mysql database

(Note: a new database named blog has been created in the database)

create database blog;
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # database engine
        'NAME': 'blog',                        # Database name
        'USER': 'root',                        # User name of the linked database
        'PASSWORD': 'password',                 # Password for linked database
        'HOST': 'domain name',                         # Domain name or ip address of mysql server
        'PORT': '3306',                        # A port number of mysql. The default is 3306


④ Change the database used by the project to Mysql

Note: Django does not use mysql database by default, so it needs to be in the project directory__ init__.py file to change the database used by the project.

import pymysql

⑤ Set time zone to China


TIME_ZONE = 'Asia/Shanghai'			#change

USE_I18N = True

USE_L10N = False				       	#change

USE_TZ = True

(4) Assign route:

Allocate the url in the urls.py file in the project directory (don't forget to create an empty urls.py file ~) in the new app directory.

from django.contrib import admin
from django.urls import path,include		#include needs to be imported

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog_server/',include("blog_server.urls")),		#Assign url

2. Create a model and map it to the database:

Create a model and map it (just execute two mapping commands. Forget to look at the previous one Model creation and mapping )To the database.
(operate the models.py file under blog_server)

from django.db import models

# Create your models here.

class BlogModel(models.Model):
    # title
    title = models.CharField(max_length=50)
    # content
    contest = models.TextField()

3. Preparation of basic framework

Preparation - create a blog in the templates directory under the project directory_ Server folder!
(for storing template files of the project ~)

(1) Preparation of parent template base.html:

(templates/blog_server/base.html file)

Just dig two holes - one hole at one title, and the titles of different pages are different; Dig a hole in one content, and the content displayed on different pages must be different.

(2) Compilation of homepage index.html:

(templates/blog_server/index.html file)

For the home page, you only need to add the implementation of url jump, so you can give two a tags in the content part!

{% extends 'blog_server/base.html' %}

{% block title %}
home page
{% endblock %}

{% block con %}
    <a href="#"> Add blog</a>
    <a href="#"> blog list</a>
{% endblock %}

View functions corresponding to the home page:

(3) Add blog page add.html:

(templates/blog_server/add.html file)

{% extends 'blog_server/base.html' %}

{% block title %}
Add page
{% endblock %}

{% block con %}
{# form In the label action It refers to where the form content is submitted. If it is not written, it will be submitted locally #}
<form method="post" action="">
    <input type="text" placeholder="Please enter article title" name="title"><br><br>
    <textarea name="content" placeholder="Please enter the article content"></textarea><br><br>
    <button type="submit">release</button>
{% endblock %}

Add the view function corresponding to the blog page:

(4) Compilation of blog list page list.html:

(templates/blog_server/list.html file)

{% extends "blog_server/base.html" %}

{% block title %}
List page
{% endblock %}

{% block con %}
Render according to the data in the database!
{% endblock %}

View function corresponding to blog list page:

Write the routes corresponding to the above view functions:

(blog_server/urls.py file)

from django.urls import path
from . import views

urlpatterns = [
    path("index/",views.index,name='index'),    #home page
    path("render_add/",views.render_add,name='render_add'),  #Add page
    path("add/",views.add,name='add'),      #Add function view for page submission
    path("list/",views.list,name='list'),       #Blog list page

Up to now, the overall framework of the project has been set up. You can run the whole project and watch the simple implementation effect:

Home page:
Add page:

Blog list page:

4. Realization of basic functions

(1) Realization of homepage function:

(2) Implementation of adding blog page function:

Write business logic for adding blog function (blog_server/views.py file):

This function has been implemented:
After clicking publish:
Check the database and find that it has been added successfully!

Imagine - after you successfully publish your circle of friends, does it just show you a "submission success"?
Definitely not! It is a list page that jumps to the circle of friends.
So use redirection. When you click "publish" and publish successfully, you will jump to the blog list page.

(3) Implementation of blog list page function:

Write blog list page to realize business logic (blog_server/views.py file):
This function has been implemented:

Now we need another function - when we click any blog title in the blog list page, we need to jump to the corresponding blog details page.

(4) Implementation of detail.html detail page:

detail.html shows all the data of a blog!

Routing of blog details page:

View function corresponding to blog details page:

Corresponding - the path jumped by the a tag wrapping each blog title in the front-end template of the blog list page shall be specified to the corresponding blog details page:
This function has been realized (click any blog title on the blog list page to jump to the corresponding blog details page!):

(5) Two new functions are introduced - deletion and modification:

Add two a tags to the blog list page (list.html):
Effect display:

First - Implementation of deletion function:

Delete the corresponding blog posts from the database and redirect to the list page!

Configure the route corresponding to the delete view function:

Change the jump link of modifying the corresponding a tag in the blog list page (list.html):

This function has been implemented:

After clicking delete, the corresponding blog will be deleted, and then jump to the original page (blog list page):

Second - Implementation of modification function:

The analysis shows that the front page required for the modification function is actually the front page for adding blog pages, so we only need to make some changes to the add.html page to realize the modification function!

Configure the route corresponding to the modified view function:

Change the add blog page (add.html) to display the add blog page when adding a blog; To display the modify blog page when modifying a blog:

{% extends 'blog_server/base.html' %}

{% block title %}
Add page
{% endblock %}

{% block con %}
{#action:Where to submit, do not write, and submit locally by default!#}
    {% if o_article %}          {# Modification page exists #}
        <form method="post" action={% url 'update' o_article.id %}>
    {% else %}                  {# Add page does not exist #}
        <form method="post" action={% url 'add' %}>
    {% endif %}

{#  Cross domain request attack because post Submit by, so take the following line, or you will report an error!#}
        {% csrf_token %}
        <input type="text" placeholder="Please enter article title" name="title" {% if o_article %}value = "{{ o_article.title }}" {% endif %}><br>
        <textarea placeholder="Please enter the article content" name="content">{% if o_article %}{{ o_article.contest }}{% endif %}</textarea><br>
        {% if o_article %}
            <button type="submit">modify</button>
        {% endif %}
            <button type="submit">release</button>

{% endblock %}

Don't forget to perfect the a tag corresponding to the modification in the blog list page:

This function has been implemented:

After clicking the blog list:

Last blog post:
Click the Modify button and modify the blog tag and content:

Click the Modify button and you will find that the modification is successful!

(6) Expand - pagination:

Part I: learning paging attributes and methods:
Use a custom list li to simulate QuerySet data in the database:

Now there is a problem that the methods of the entire instance object on page n are not interconnected with the Paginator instance object. What should we do if we use the Paginator instance object method after obtaining the instance object on page n?

Part II: combined with the project:

① Change of view function (pagination of blog list page)

② List template path change (pass parameter num to it: realize the transformation of page number)

③ Change of list.html template file (realize pagination display; up and down pagination transformation can be carried out)

{% extends "blog_server/base.html" %}

{% block title %}
List page
{% endblock %}

{% block con %}
    <li><h2>Article title</h2></li>
        {% for foo in pages %}
                <a href={% url 'detail' foo.id %}>{{ foo.title }}</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <a href={% url 'edit_blog' foo.id %}>modify</a>
                <a href={% url 'delete_blog' foo.id %}>delete</a>
        {% endfor %}
    {#    .number The method is to obtain the page number of the current page;#}
    {#    .previous_page_number The method is to obtain the page number of the previous page;#}
    {#    .next_page_number The method is to obtain the page number of the next page;#}
    {#    .has_previous The method is to judge whether there is a previous page;#}
    {#    .has_next The method is to determine whether there is a next page.#}
    {% if pages.has_previous %}
            <a href="{% url 'list' pages.previous_page_number %}">previous page</a>
    {% else %}
            <a href="javascript:">previous page</a>
    {% endif %}

    {% if pages.has_next %}
            <a href="{% url 'list' pages.next_page_number %}">next page</a>
    {% else %}
            <a href="javascript:">next page</a>
    {% endif %}

{% endblock %}

Source code of the whole project:

   you can click the following - > add a private VX number - > please indicate that you are from CSDN [will send you the source code of this small project], which will pull you into the technical exchange group (the group involves big people in various fields, and any problems can be discussed ~) - > learn from each other & & make common progress (don't bother if you are not sincere):

Tags: Python Django Pycharm

Posted on Mon, 20 Sep 2021 08:37:16 -0400 by Thethug