Cloud server usage

What is a cloud server

  • The server

    Essentially a computer, the difference with a PERSONAL computer is:

    1. Purpose: Provide network application service
    2. Start time: 24 hours uninterrupted
  • Configure the server yourself or rent the entire server

    1. Configure trival
    2. Performance not easy to change
    3. Vulnerable to attack
    4. Low actual utilization
  • What is a cloud server

    1. Provided by the cloud server carrier
    2. There is no need to purchase a physical server separately
    3. A collection of servers and then divided into independent space as the user’s host

How to choose a cloud server

  • An Internet company that provides cloud servers

    • Baidu cloud
    • Tencent cloud
    • Ali cloud
    • Meituan cloud
    • Netease cloud
    • amazon web services
    • ucloud
    • Google Cloud Platform
  • How to choose

    • Large manufacturers cloud server quality assurance, slightly higher prices

    • VPS: Similar to cloud servers with low price and instability

How do I use a cloud server

  • Buy cloud server – Ali cloud as an example

    • Ali cloud official website: cn.aliyun.com/
    • Home page – New Events – Get on the road and look for some free, trial, low-cost packages (if you can complete student certification, you can buy a student-only plan, very cheap)
    • Cloud Computing Foundation: Select a lightweight application server
    • Pre-installed environment: System image, Ubuntu 16.04 64-bit (novice friendly), region selection: See where most users choose
  • Buy cloud server – Ali Cloud as an example (if none can participate in the offer)

    • Ali Cloud Management Console – Cloud computing infrastructure services
    • Cloud service ECS- Instance – Create an instance
    • Basic configuration
      • Billing method: package annual monthly/pay by volume, according to their actual situation
      • Region: where do most users choose, or choose a preferential region
      • Example: The first TAB is “latest generation only”, we don’t need it, switch to “All Generations”.
        • Architecture: x86 computing
        • Classification: Practice does not need too advanced configuration, can choose [entry level (shared)]
      • Public image: Ubuntu 16.04 64-bit
      • Storage: Efficient cloud disk, 40 GB by default
      • Buy cycle: buy one week first
    • Network and Security Group
      • Network: Default private network, do not change
      • Public network bandwidth: pay by fixed bandwidth or by traffic
      • Security group, default
      • Elastic NETWORK adapter, default
    • The system configuration
      • Login credentials, passwords are relatively simple, low security
      • Instance name
    • Group set up
      • The default
    • Make sure the order
      • Order, pay
  • Using a Cloud Server

    • Ali Cloud Management Console – Cloud Computing Basic Services: display server list
    • The instance details
    • Click Remote connection to enter the server operation page
  • Terminal control and transmission tools

    • Remotely connect to server tools
      • win puTTY
    • Transfer management server file utility
      • win WinSCP
  • Logging In to the Server over SSH

    • macOS
      • Terminal-inputSSH root@Server IP address
      • Enter the password. The password is blind and will not be displayed
  • Import files using an SFTP client

    • win

    • mac?

Basic Linux commands

  • An example of a blog site
    • Create a project: On the server, enter the commandmezzanine-project makerbean
    • Create the database: python3 manage.py createdb
    • Enter the public IP address of the cloud server we purchased
    • Enter your email address and password
    • Whether to add a Demo page? Yes
    • runSudo python3 manage.py runserver 0.0.0.0:80
    • It can be accessed through public IP (this is a blog project of others, and I will learn to build it myself later)
    • If the access fails, it may be due to firewall problems. Check whether port 80 is accessible to all in the cloud server ecS-security group rules.

homework

Djiago Basics and front end introduction

Why Djiago

  • Free and open source
  • feature-rich
  • To develop rapidly
  • It is highly extensible
  • The template system
  • Background management

Create a Python virtual environment

Role: Multiple projects may require different versions of packages and libraries

Steps:

  • Create a new project folder, such as Website
  • Use the CD command at the command line to go to website
  • Enter python3 -m venv djangoenv
  • A djangoenv folder appears in the website folder
  • Windows type djangoenv\scripts\activate to activate the virtual environment
  • MAC Enter source djangoenv/bin/activate to activate the virtual environment
  • The command line starts with the word (djangoenv)

Install Django and create a new project

  • PIP install Django

    ERROR: Could not find a version that satisfies the requirement django (from versions: none) ERROR: No matching distribution found for django

    • Solution: Upgrade the PIP commandpip install --upgrade pip
  • Once installed, type Django-admin startProject my_blog to create a website project

    My_blog is the name of the Django website project. Name it yourself. Don’t use names such as Django or test to create conflicts.

  • Initialize the purpose of the file

    • Manage.py is a web site management tool that can be invoked from the command line
    • Under my_blog:
      • Init. py tells Python that the folder is a module
      • Some configuration of setting.py my_blog project
      • Individual url declarations within the urls.py website
      • Wsgi. py Web server interface to Django projects
  • Check whether the Djngo project is installed successfully

    • cd my_blog

    • python3 manage.py runserver

      As shown below, no error is reported, and the red message can be ignored for the time being:

    • Can visit http://127.0.0.1:8000/

Introduction to the front

  • What is the front end? What is the back end

    • Front end: what you can see, graphics, text
    • Back-end: Storage and logical data
  • What does front-end development use?

    • Debug web sites for Chrome
  • The front end has three important aspects

    • HTML

      • HyperText Markup Language
      • The most basic elements of a web page
      • Organize content (text, images, video) by way of markup language
      • HTML Element parsing
        • < Start tag attribute name = Attribute value > Content < End tag >

          <p class='info-list'> This is a paragraph <\p>

      • Create an HTML file and save it as index.html
        
                    
        <html>
        <head>
        	<title>My blog</title>
        </head>
        <body>
        	<h1>A tranquil night</h1>
        	<p>The moon is shining before the window</p>
        	<p>Suspected frost on the ground</p>
        	<p>Looking up, I find the moon bright</p>
        	<p>Bowing, In homesickness I'm drowned</p>
        </body>
        </html> 
        Copy the code
    • CSS

      • Cascading Style Sheets

      • It defines how a page should display elements, such as whether the paragraph is on the right or left, what color the text is, what font it is, and so on.

      • Create a CSS file and save it as index-style.css

        p {
        	color:blue;
        	font-family:KaiTi;
        }
        Copy the code
      • Link CSS to HTML by adding under

        in index.html

        
                    
        <html>
        <head>
        	<title>My blog</title>
        	<! Create a link between CSS and HTML
        	<link rel="stylesheet" type="text/css" href="index-style.css"> 
        </head>
        <body>
        	<h1>A tranquil night</h1>
        	<p>The moon is shining before the window</p>
        	<p>Suspected frost on the ground</p>
        	<p>Looking up, I find the moon bright</p>
        	<p>Bowing, In homesickness I'm drowned</p>
        </body>
        </html> 
        Copy the code
      • CSS analytical

        Selector {property name: property value; }Copy the code
      • Id and class-ID in each HTML file only one – class can have more than one

      • The box model

        • Between the content and the box border is the padding, or inside margin
        • Between the border and other elements outside the border is the margin, or margin
    • JavaScript

      • A programming language used primarily for the front end

      • Provide dynamic and interactive effects for the site

      • Create a js file and save it as index.js

        // Define a string variable
        var alertText="hello world";
        // A prompt box pops up on the page
        alert(alertText);
        Copy the code
      • To establish the relationship between JS and HTML, add a

        <script type="text/javascript" src="index.js"></script>

homework

Django view

Django views and urls

  • python manage.py runserver

    When we run this command, we are prompted:

    You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.

    Run ‘python manage.py migrate’ to apply them.

    Follow its instructions and run Python manage.py Migrate. After running this command, you will see db.sqlite3 in the my_blog folder, which is the base database of your site

  • Create a New Django App

    • From the command line, go to the django project folder and type Python manage.py startApp blog

    • Create a blog folder after you finish

  • Add your App to setting.py

    • In the Djingo project folder there is a folder with the same name as the current projectsetting.pyFile,INSTALLED_APPSAdd a Blog
    INSTALLED_APPS = [
    'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'blog',]Copy the code

Django’s MTV mode

Brower — browser; URL – web address; View — View; Model – a Model; Database — Database; The Template, Template

view

  • Writing view functions
    • Open the blog/views.py file, the default interface is as follows:

    • Write views.py and add the following statement:

      from django.shortcuts import render
      from django.http import HttpResponse
      # define an index function to handle the home page request. Request contains the content of the HTTP request sent by the user's browser
      def index(request):
          HttpResponse returns a text directly to the user
      	return HttpResponse("Welcome to my blog.")
      Copy the code

The url

  • Create urls. Py

    • Create a new file under the Blog folderurls.py, used to handle url parsing
    • writeurls.py, add the following
      from django.urls import path
      from . import views
      
      urlpatterns = [
      	path(' ',views.index,name='index'),]Copy the code
  • Project urls. Py

    • Having urls.py under my_blog is not the same as creating a new file called urls.py under blog. The difference is that urls.py under blog is the url that manages the blog system, while my_blog is the url that manages the entire project

    • Open the my_blog/urls. Py

      Indicates the configuration.ip:port/adminThe url we visit to start the servicepython3 manage.py runserverAfter the visithttp://127.0.0.1:8000/admin, you can see an administrator login interface

  • Create an administrator account

    • Run Python manage.py createsuperuser at the project root

    • Enter the username

    • Enter the Email address

    • Enter password. If the password is not displayed, blind dialing is performed

  • Log in to the background as an administrator

    • Run Python manage.py runserver

    • The browser open http://127.0.0.1:8000/admin, enter the username and password to log in

    • Click user to manage the information and permissions of existing users

  • Configure urls.py for the project

    • Is amended as:

      from django.contrib import admin
      # add an include
      from django.urls import path,include
      
      urlpatterns = [
          path('admin/', admin.site.urls),
          When the url is /blog, pass it to blog.urls
          path('blog/',include('blog.urls')),]Copy the code
    • Run python manage. Py runserver then executes, visit http://127.0.0.1:8000/blog/, appeared in the view to write that sentence:

    • Let’s go through the process here

      The urls.py file of the project has path(‘blog/’,include(‘blog.urls’)), which means that when the url is http://ip:port/blog/, it will look for the urls.py file in the blog. Path (“,views.index,name=’index’) =’ blog ‘=’ blog’ =’ blog ‘=’ blog

  • More complex url handling

    • Modify urls.py in the blog file by adding a line of path(‘

      ‘,views.blog_detail,name=’blog_detail’)



    • ‘ indicates that the url is a number and blog_id exists

    • Add a blog_detail function to views.py and restart the service as follows:

      def blog_detail(request,blog_id):
          return HttpResponse("This is my {} blog".format(blog_id))
      Copy the code

    • For different types of variables, see:

homework

Development: SEO

  • SEO, Search Engine Optimization
  • The impact of web addresses on SEO
    • Xxx.com/zhongjie-ev…

    • Xxx.com/agency-ever…

      This is better than the last web address, because you know what the web address is, right

    • xxx.com/blog/1

      This website does not know what content will be completely, SEO is very poor

  • So take this into account when designing a web site
  • Complex Web site Demo
    • Modify the blog fileurls.py, add a linepath('<slug:blog_title>',views.blog_title,name='blog_title')
    • Add corresponding functions in views.py
          def blog_title(request,blog_title):
              return HttpResponse("This is my blog with the title {}".format(blog_title))
      Copy the code
    • The effect is as follows:

Djingo template

Template demo

  • Create the templates folder under your blog

  • Add blog homepage HTML

    • Create a new blog_index.html in the Templates folder
    • Write a simple welcome at blog_index.html
      
                
      <html>
      <head>
      	<title>My blog - home page</title>
      </head>
      <body>
      	<h1>welcome to my blog</h1>
      	<h3>study hard and make progress every day</h3>
      	<ol>
      		<li>Python</li>
      		<li>C++</li>
      		<li>Java</li>
      	</ol>
      
      
      </body>
      </html>
      Copy the code
  • Change the index function in blog/views.py to:

    def index(request):
        Blog_index.html # render = blog_index.html
        return render(request,'blog_index.html')
    Copy the code
  • Visit http://127.0.0.1:8000/blog/, is blog_index. HTML content

Understand the template system

Specify a template to render in views.py, for example:

def index(request):
    return render(request,'blog_index.html')
Copy the code

Django will automatically search the templates folder for each App and find it in blog/templates/blog_index.html.

  • There may be HTML files with the same name in different apps, which may cause conflicts.
    • Create a templates folder with the same name as your current app and put your HTML files in that folder, the original oneblog/templates/blog_index.htmlInstead,blog/templates/blog/blog_index.html
    • Modify theviews.pyContent:return render(request,'blog/blog_index.html')
    • HTML file names are no longer called for standardizationblog_index.htmlInstead,index.htmlSo the correspondingview.pyChange the content ofreturn render(request,'blog/index.html')

Django templates are advanced

  • Variable {{variable}}

    • Replace the h1 content in index.html with {{welcome}}

    • Add a dictionary to the index function in views.py

      def index(request):
      	return render(request,'blog/index.html', {'welcome':'Welcome to the front page of this stupid blog'})
      Copy the code
    • Where the welcome variable is replaced

  • Apply colours to a drawing list

    • In views.py, change the index function to the following statement:

      def index(request):
      	language_list=['Python'.'C++'.'Java']
      	return render(request,'blog/index.html', {'welcome':'Welcome to the front page of this stupid blog'.'language_list':language_list})
      Copy the code
    • Change the code in index. HTML to {% code %} for the code logic

      Render the list as we commented out the code

      
                
      <html>
      <head>
      	<title>My blog - home page</title>
      </head>
      <body>
      	<h1>{{welcome}}</h1>
      	<h3>study hard and make progress every day</h3>
      	<ol>
      	<! - for loop -- >
      	{%for item in language_list%}
      		<li>{{item}}</li>
      	<! HTML files will not be indent -->
      	{%endfor%}
      	</ol>
      	<! -- <ol> <li>Python</li> <li>C++</li> <li>Java</li> </ol> -->
      </body>
      </html>
      Copy the code
    • Gets the number of cycles forloop.counter indicates the number of cycles, starting at 1

      <li>{{item}} -- {{forloop.counter}}</li>

      To count from 0, use forloop.counter0

  • Render a dictionary

    • In views.py, change the index function to the following statement:

      def index(request):
      	language_list=['Python'.'C++'.'Java']
      	link_dict={
      	'douban':'https://www.douban.com/'.'baidu':'https://www.baidu.com/'.'google':'https://www.google.com.hk/'}
      	return render(request,'blog/index.html',
      	{'welcome':'Welcome to the front page of this stupid blog'.'language_list':language_list,
      	'link_dict':link_dict})
      Copy the code
    • Add the following code to in index.html:

      <a href="{{link_dict.douban}}"< p style = "max-width: 100%; clear: both; min-height: 1em"{{link_dict.baidu}}"< p style = "max-width: 100%; clear: both; min-height: 1em"{{link_dict.google}}"> Google < / a >Copy the code

  • Conditional judgment in templates

    • In views.py, change the index function to the following statement:

      def index(request):
      	language_list=['Python'.'C++'.'Java']
      	link_dict={
      		'douban':'https://www.douban.com/'.'baidu':'https://www.baidu.com/'.'google':'https://www.google.com.hk/'
      	}
      	flag=True
      	return render(request,'blog/index.html',
      		{'welcome':'Welcome to the front page of this stupid blog'.'language_list':language_list,
      		'link_dict':link_dict,
      		'flag':flag}
      		)
      Copy the code
    • Add an if judgment to in index.html:

      
                
      <html>
      <head>
      	<title>My blog - home page</title>
      </head>
      <body>
      	<h1>{{welcome}}</h1>
      	<h3>study hard and make progress every day</h3>
      
      	{% if flag %}
      		<p>The window was full of moonlight, like frost on the ground</p>
      	{% else %}
      		<p>There's no content here</p>
      	{% endif %}
      	
      	<a href="{{link_dict.douban}}">douban</a>
      	<a href="{{link_dict.baidu}}">baidu</a>
      	<a href="{{link_dict.google}}">Google</a>
      	
      	<ol>
      	{%for item in language_list%}
      		<li>{{item}} -- {{forloop.counter}}</li>
      	{%endfor%}
      	</ol>
      
      </body>
      </html>
      Copy the code

  • Check whether the user is logged in

    • Index.html added

      {% if request.user.is_authenticated %}
      	<p>{{request.user.username}},welcome</p>
      {% else %}
      	<p>Please log in</p>
      {% endif %}
      Copy the code

      When I log out of 127.0.0.1:8000/admin:

  • Use an existing blog template

    Startbootstrap.com/ Select your preferred template

    • For example, select blog under Themes

    • Select the Clean Blog template

    • Download the template and decompress it

    • Replace our previous index. HTML file with the index. HTML file downloaded from the template, you can see the picture as shown, because we can’t find relevant JS, CSS, images and other materials

    • Material copied

      • Create a new static folder in the root directory of your project

      • Create a corresponding blog folder under the static folder, copy the downloaded materials CSS, IMG, JS, and vendor into the blog folder

    • Modify the setting. Py

      • Open thesetting.py, added in the last lineSTATICFILES_DIRS=[os.path.join('static')]
    • Modified index. HTML

      Static :{% load static %}

      Find all CSS, JS, images and modify the link as follows:

      The original:

      <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

      Is amended as:

      <link href="{%static 'blog/vendor/bootstrap/css/bootstrap.min.css'%}" rel="stylesheet">

      Search for the keywords CSS, js, img, and add blog/ :

      <header class="masthead" style="background-image: url('{%static 'blog/img/home-bg.jpg'%}')">

      <script src="{%static 'blog/vendor/jquery/jquery.min.js'%}"></script>

      <script src="{%static 'blog/vendor/bootstrap/js/bootstrap.bundle.min.js'%}"></script>

      If an error occurs, you can check the error on the terminal or the web console, for example:

      Error 404, forgot to add blog/

  • Modify the content of the blog template

    • <title> Welcome to my blog </title>

    • <h1>DayBreak's Blog</h1>

    • <span class="subheading" style =" max-width: 100%; clear: both; min-height: 1em; </span>

  • Modify index.html to add template parameters

    • Find relevant content in index. HTML

      Each

      is a set of links corresponding to each blog detail page

    • Modify the code as follows

      {% for post in post_list %}
      <div class="post-preview">
        <a href="{{post.link}}">
          <h2 class="post-title">
            {{post.title}}
          </h2>
          <h3 class="post-subtitle">
            {{post.subtitle}}
          </h3>
        </a>
        <p class="post-meta">Posted by
          <a href="#">{{post.author}}</a>
          {{post.date}}</p>
      </div>
      <hr>
      {% endfor %}
      Copy the code
  • Modify views. Py

    def index(request):
    	post_list=[
    		{
    			'link':'/first_blog'.'title':'shock! This is the headline of the first blog post..'subtitle':'Don't be shocked, this is the subtitle of the first blog post.'.'author':'DayBreak'.'date':'2020-03-27'
    		},
    		{
    			'link':'https://www.baidu.com'.'title':'shock! This is the headline of the second blog post..'subtitle':'Don't be shocked, this is the subtitle of the second blog post.'.'author':'DayBreak'.'date':'2020-03-27'}]return render(request,'blog/index.html',
    		{'post_list':post_list}
    		)
    Copy the code

homework

Django models

Know the database

  • A repository for storing data
  • What is data?
    • The name, sex and academic record of the student;
    • User’s bank card number, password, balance, transaction record
    • Site login account, password, comments
    • Game user name, equipment, attributes, levels

How is data stored in the database

  • Tables store information

  • There may also be different relationships between tables

Databases in Django

  • Open the models.py file in the Blog application

  • Add the following

    # create a new table called POST from models.Model
    class Post(models.Model):
    
    	# has a title attribute
    	title=modesl.CharField(max_length=80)
    Copy the code
  • Synchronizing databases

    • Run at rootpython manage.py makemigrations
    • If the following information is displayed, the Post model is created
    • Continue command executionpython manage.py migrate
    • Get the following prompt

Use admin background system to manage data

  • Run Python manage.py runServer to start the server

  • Modify admin.py in the blog folder

    from django.contrib import admin
    from .models import Post
    
    # Register your models here.
    admin.site.register(Post)
    Copy the code
  • Log in to the admin background system

    • Visit http://127.0.0.1:8000/admin to see a new columns

  • Admin Manages the background system

    • Click on Posts and you can see that nothing has been posted yet

    • Click ADD POST to ADD a POST title directly

    • Enter the content in the title and SAVE. Post project(1) is called after saving, which is not intuitive

    • Modify models.py in the blog folder

      class Post(models.Model):
      
      # has a title attribute
      title=models.CharField(max_length=80)
      
      def __str__(self):
      		return self.title
      Copy the code

      At this point, this shows the content of the title that you typed

Design the Blog model

  • A blog post related to the following information:

    • The title
    • subtitle
    • The author
    • The published date
    • The label
    • classification
    • Post content
    • Link to blog
    • Number of likes (optional)
    • Reading amount (optional)
  • The various models available in Django

    Currently commonly used: – CharField simple text model – DateTiemField time model – TextField large text model

  • Design simple version of blog post model

    What are the problems with this design?

    The existence of authors, labels and categories in the same table will result in a large number of duplicate contents, which are not easy to retrieve and modify.

  • Design advanced version of blog post model

Blog base template

  • Models.py adds some base models

    class Post(models.Model):
    
    	title=models.CharField(max_length=80)
    	subtitle=CharField(max_length=120)
    	publish_date=models.DateTimeField()
    	content=models.TextField()
    	link=models.CharField(max_length=200)
    
    	def __str__(self):
    			return self.title
    Copy the code
  • Associated author model

    from django.db import models
    from django.contrib.auth.models import User`
    
    class Post(models.Model):
    
    title=models.CharField(max_length=80)
    subtitle=CharField(max_length=120)
    publish_date=models.DateTimeField()
    content=models.TextField()
    link=models.CharField(max_length=200)
    # Use ForeignKey() to associate the field author with another model
    author=models.ForeignKey(User,on_delete=models.CASCADE) 
    
    def __str__(self):
    		return self.title
    Copy the code

Create a classification model and label model

Add two classes and complement the Post class

class Category(models.Model):
	"""Classification"""
	name = models.CharField(max_length=100)
	def __str__(self):
			return self.name

class Tag(models.Model):
	"""Label"""
	name = models.CharField(max_length=100)
	def __str__(self):
			return self.name

class Post(models.Model):
	title=models.CharField(max_length=80)
	subtitle=models.CharField(max_length=120)
	publish_date=models.DateTimeField()
	content=models.TextField()
	link=models.CharField(max_length=200)
	# Use ForeignKey() to associate another model
	author=models.ForeignKey(User,on_delete=models.CASCADE) 
	category=models.ForeignKey(Category,on_delete=models.CASCADE) 
	Use MangToManyField() to associate another model
	tag=models.ManyToManyField(Tag,blank=True)

	def __str__(self):
			return self.title
Copy the code
  • ForeignKey() and ManyToManyField()

    • One-to-many relationships, using ForeignKey()

      An article has only one category, and there are multiple articles under one category

    • Many-to-many relationships, using MangToManyField()

      An article can have multiple tags, and one tag will correspond to multiple articles

  • Two new models are created, so add them in admin.py

    from django.contrib import admin
    from .models import Post
    from .models import Category
    from .models import Tag
    
    # Register your models here.
    
    admin.site.register(Category)
    admin.site.register(Tag)
    admin.site.register(Post)
    Copy the code

Run Djangos admin commands

  • Run Python Manage.py Makemigrations whenever you modify the models.py file

    You will be prompted:

    Means:

    Select option 1 and set the default value to 1, except datetime to timezone.now

    Successful creation:

  • Run Python Manage. py MakemigRations every time you run Python Manage. py magRate

  • Note: If python manage.py magrate keeps getting errors, try deleting the db.sqlite3 file under my_blog, re-running Python manage.py magrate, and re-creating the admin account.

Admin Background View

  • Enter the background management, you can see the new Category, Tag

  • Click on posts-Add post to Add the fields we wrote

  • Add categories, such as programming categories

  • Add tags, such as Python tags

  • Enter post again, you can find optional programming Category, Tag can choose Python, directly click ➕ to add

Extract real blog information from the database

  • Modify theviews.py
    • Introduce Post model from. Models import Post

    • List all post.objects.all ().order_by(‘-publish_date’);

    • Modified as follows:

      from django.shortcuts import render
      from django.http import HttpResponse
      from .models import Post
      
      # Create your views here.
      
      def index(request):
      	post_list=Post.objects.all().order_by('-publish_date')
      	return render(request,'blog/index.html', {'post_list':post_list})
      Copy the code

Design blog details page url

  • Each post have an English website, such as 127.0.0.1:8080 / blog/django – of course – 1

  • The background link only needs to fill in the django-course-1 section

  • Modify the index.html blog details page link to blog/link

    <a href="/blog/{{post.link}}">

  • Change time there to our time variable

    <p class="post-meta">Posted by
            <a href="#">{{post.author}}</a>
            {{post.publish_date}}</p>
    Copy the code
  • Modify urls. Py to change the blog_detail parameter to blog_link path(‘

    ‘,views.blog_detail,name=’blog_detail’),

  • Modify views.py from Django. shortcuts import render,get_object_or_404

    Get_object_or_404: extracts some data from a model based on keywords. If no data is found, a 404 page is returned

    def blog_detail(request,blog_link):
        post=get_object_or_404(Post,link=blog_link)
        return HttpResponse(post.content)
    Copy the code
  • Configure a blog in the admin background to see the effect

Add blog details page template

One of the templates we downloaded was a post.html file, the template for our blog details page, which we used in our project under/Templates /blog in our app.

  • Modify views. Py

    def blog_detail(request,blog_link):
    
    	post=get_object_or_404(Post,link=blog_link)
    	# Return to blog details
    	return render(request,'blog/post.html', {'post':post})
    Copy the code
  • Modify the post. HTML

    Change the js, CSS, and img paths as we did with index.html:

    <link href="{%static 'blog/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

    Modify title, title, subtitle, Author, body, and date:

More beautiful text typesetting

Method 1: Write HTML code directly in the background content, which is more troublesome;

Method 2: Write blog posts in Markdown format (recommended)

  • PIP install markdown2

  • Modify views. Py

    def blog_detail(request,blog_link):
    
    	post=get_object_or_404(Post,link=blog_link)
    	post.content = markdown2.markdown(post.content)
    	# Return to blog details
    	return render(request,'blog/post.html', {'post':post})
    Copy the code
  • Background blog content is edited with Markdown syntax

    What can I do if the tag is not rendered?

    In the post. {{post. The content}} in the HTML is modified to {{post. The content | safe}}

    Legacy issues, which do not seem to support the display of code blocks, to be resolved

Adjust the url

Now the URL is 127.0.0.1:8000/blog/ home page, and we want 127.0.0.1:8000 to be the home page

  • Change the urls.py of my_blog
    urlpatterns = [
        path('admin/', admin.site.urls),
        path(' ',include('blog.urls')),]Copy the code
  • Modify your blog’s urls.py
    urlpatterns = [
    	path(' ',views.index,name='blog_index'),
    	path('blog/<slug:blog_link>/',views.blog_detail,name='blog_detail'),]Copy the code

How to publish the website

  • Purchase a server and domain name
    • The server is shown in the first section of this article

    • The domain name

      • Domestic: wanwang.aliyun.com
      • Abroad: godaddy.com
      • .co/.com and other domain names require real name authentication
    • Server or domain name is bought in home, need undertakes put on record, if did not put on record, can be dropped by the wall likely

    • After the purchase, set domain name resolution to indicate the server IP address to which the domain name refers

Django deployment

(Without going into details, Google)

  1. Install uwsgi

  2. Configuration uwsgi. Ini

    Example:

  3. Install nginx

  4. Configure nginx

  5. Start uWSGi uWSGi –ini uwsgi.ini

  6. Start the nginx

Several common problems in server use

  1. Maybe the database did not fill in our hosts
  2. Port 80 May have been enabled before. Turn off port 80
  3. The IP address is incorrect. The IP address of the public network is required
  4. Even if there is no operation for a period of time, it will automatically break
  5. Network connection problem
  6. Install a Screen application

homework

【 —- END —-】