Django learning - building a personal blog
background
The on-the-job graduate students have been in a state of ignorance after adjusting their majors and won't do anything. In the first semester, the teacher arranged to build a blog as the final grade. There was no way but to study everywhere and record the process.
Process record
Tool: pycharm anaconda
1, Preparatory work
1. Install django, and use pip install django in cmd
2. Open pycharm and create a new project1 project
Add project - mysite. Myjang3
4. Input cd mysite in the terminal to open the mysite just now
5. Input Python manage Py startapp blog to create a blog application.
6. Next, in settings PY_ Apps tells the project that I have built a blog application.
7.Python has its own SQLite3 database, so it is not set.
8. Django helps us connect with the database by default, so we don't use sql statements. We just need to synchronize the database and generate the relevant tables. Enter three steps in the terminal:
(1) Update the structure of the whole project to ensure that the existing table structure is complete before introducing the new table structure py migrate
(2) Notification framework to automatically detect changes in the model layer of blog application. Python manage py makemigrations blog
(3) Create a table structure in the blog application Python manage py migrate blog
9. Create an administrator account and enter: Python manage Py createsuperuser, then enter the user name and password, and finally enter y to confirm.
Terminal input Python manage Py runserver test blank page
10. Follow the address with / Admin( http://127.0.0.1:8000/admin )Test management interface.
11. This concludes the preparatory work. (Note: there are no tables in the database at this time)
2, Design a fixed page without database update (this paragraph does not involve the model layer)
1. There are 3 pages in total, and the first page is home1 HTML, which has fixed content. Click the content to jump to the second topic page home2 HTML, and then click the topic content to jump to home3 on page 3 html.
2. Open MySite / blog / views Py file and modify the views file (as a view, that is, the content for everyone to see)
import datetime from django.shortcuts import render # home page def home1(request): context = {} context['name'] ='python programming' context['description'] = 'python Basic knowledge web development' context['time_now'] = datetime.date.today().strftime('%Y-%m-%d') return render(request, 'home1.html', context)
3. The content views has been set up. To establish a connection with the web page, modify URLs Py file
from django.contrib import admin from django.urls import path from django.conf.urls import url from blog import views urlpatterns = [ path('admin/',admin.site.urls), url(r'^$',views.home1), # home1 ]
4. Make a template to separate the content and presentation. First configure settings and tell the project that I have a template (remember to import os)
'DIRS': [os.path.join(BASE_DIR,"templates")],
5. Create the templates directory under the blog project (mysite/blog/templates /), and create home1 HTML file, put board things in one by one.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Boards</title> </head> <body> <center> <h1>caihuihui Blog</h1> <!-- title --> <table border="1"> <thead> <tr> <th>Board</th> <!-- Header --> </tr> <tr> <td>{{ name }}<br> <!-- And views Topic 1 corresponding to layer --> <small style="color: #888 "> {{description} < / small > <! -- subject description corresponding to the views layer, small font -- > </td> </tr> <h2><small style="color: #C71585 "> today is {{time_now}}. Welcome to < / small ></h2> </table> </center> </body> </html>
6. At this point, the terminal will refresh automatically. After clicking, the whole views will be presented
7. However, the home page just now is really ugly. To beautify it, you have to use css(CSS is equivalent to a format template, which can be written or downloaded by yourself). First, create a new static path under the blog. Reopen css download address , unzip the bootstrap Put in min.css. At the same time, create an images folder under static and put three pictures named hd1, hd2 and hd3 as the background of the three web pages
8. tell settings that we have css.
STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]
9. Next, use css format to set home1 HTML, make it look better, change home1 html. Where {% load static%} is a prerequisite for importing css, and < body style = "background image... > is to add a background image
<!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Caihuihui Personal blog</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body style="background-image: url({% static 'images/hd1.jpg' %});background-size:100%;" > <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item active">Caihuihui Personal blog</li> </ol> <table class="table"> <thead class="thead-dark"> <tr> <th>Board</th> </tr> </thead> </tr> <tr> <td><a href={% url 'home2' %}> {{ name }} </a><br> <!-- And views The topic corresponding to layer 1 and set to jump to level 2 page home2 --> <small style="color: #888 "> {{description} < / small > <! -- subject description corresponding to the views layer, small font -- > </td> </tr> <h2><small style="color: #C71585 "> today is {{time_now}}. Welcome to < / small ></h2> </table> </div> </body> </html>
14. In the figure above, if you want to click the python theme to enter the next web page to display the topic, click home1 < a href = {% URL 'home2'%} > {{name}} in the HTML code is the statement to realize the jump (it is no longer indicated later. You have to run after setting all the level 3 pages, otherwise it will prompt the error that the jump statement cannot find the next page). Now start designing the level 2 detail page interface home2:
Views adds content to jump to home2
# Topic page def home2(request): context = {} context['topic1'] = "Django Strategy" context['starter1'] = 'caihuihui' context['last_updated1'] = datetime.datetime.now() return render(request, 'home2.html', context)
Urls add path
path('home2/',views.home2,name='home2'),
Create a new home2.0 template HTML page
<!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Caihuihui Personal blog</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body style="background-image: url({% static 'images/hd1.jpg' %});background-size:100%;" > <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item active">Caihuihui Personal blog</li> </ol> <table class="table"> <thead class="thead-dark"> <tr> <th>Board</th> <th>starter</th> <th>last updated</th> </tr> </thead> <tr> <td><a href={% url 'home3' %}> {{ topic1 }} </a></td> <td>{{ starter1 }}</td> <td>{{ last_updated1 }}</td> <td></td> </tr> </table> </div> </body> </html>
15. Continue to realize. Click "Django introduction" to enter the level 3 home3 content interface.
Views adds what is displayed after jump
# Content page def home3(request): context = {} context['hello'] ="hello world!" context['name'] = 'Caihuihui' context['list'] = "Django yes Python An open source model driven by programming language-view-Controller( MVC)Stylized Web Application framework. use Django,We can create high-quality, easy to maintain, database driven applications in a few minutes." return render(request, 'home3.html', context)
Urls add path
path('home2/home3/',views.home3,name='home3'),
Template create home3 HTML page
<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>board/home2/hello</title> </head> <body style="background-image: url({% static 'images/hd3.jpg' %});background-size:100%;" > <h1>{{ hello }}</h1> <h2>{{ name }}</h2> <table border="1"> <tr> <th>{{ list }}</th> </body> </html>
So far, it is completed to realize the web page with css and click the relevant content to jump three times.
3, Design a fixed page with database update (involving the model layer. The administrator can enter the model layer through admin to operate the database to add content, and display the topic, creator starter and creation time last_updated on the home2 page in real time. Admin can operate addition, deletion, modification and query, so it is no longer set separately)
1. In the preparation of Chapter 1, admin was created, but it is empty. Now we need to define the structure of the table in the database and modify the models Py, create a Content class and define topic, starter, details and last_updated has four attributes as the mapping type in ORM.
from django.db import models class Content(models.Model): topic = models.CharField(max_length=255) # Topic attribute starter = models.CharField(max_length=255) # Creator properties details = models.CharField(max_length=255) # Content properties last_updated = models.DateTimeField() # Create time attribute
2. Modify admin. Under blog Py register the Content class just defined
from django.contrib import admin from .models import Content class ContentAdmin(admin.ModelAdmin): list_display = ['topic', 'starter','details', 'last_updated'] # Four headers can still be seen in the background admin.site.register(Content,ContentAdmin)
3. Execute database synchronization and input at the terminal
python manage.py makemigrations blog
python manage.py migrate
4. At this point, you can see something in the model layer by entering / admin again. After clicking it, you can also see the defined topic, starter, details and last_updated
6. Unfortunately, home2 in the previous chapter 2 shows fixed content, which has occupied views and urls. It can no longer be transferred to the same templates page, that is, one template can't have two views, and errors will occur when configuring urls (I stuck for several days, and finally found a foreign explanation: Link here , I have no choice but to modify the previous home2 and home3 contents. Alas
7. Start to modify. home1 does not involve the database, but the fixed content. Regardless, change the views of home2.
After change:
# Topic page def home2(request): #It is used for home1 jump, and the database is also used to obtain the display from blog.models import Content blog_list = Content.objects.all() # Get all data return render(request, 'home2.html',{'blog_list': blog_list})
8.urls does not need to be modified, but home2 html
After modification:
<!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Caihuihui Personal blog</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body style="background-image: url({% static 'images/hd1.jpg' %});background-size:100%;" > <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item active">Caihuihui Personal blog</li> </ol> <table class="table"> <thead class="thead-dark"> <tr> <th>Board</th> <th>starter</th> <th>last updated</th> </tr> </thead> <tbody> </tbody> {% for blog in blog_list %} <tr> <td> <a href={% url 'home3' %}> {{ blog.topic }} </a> </td> <td class="align-middle">{{ blog.starter }}</td> <td class="align-middle">{{ blog.last_updated }}</td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
9. So far, click home1 fixed content to jump to home2 page, which obtains the database and displays it in real time, and click the title content to jump to home3 details page.
10. Since home3 was still a fixed content before, it has to be changed... Because of limited capacity, it is temporarily modified to jump to home3 after clicking to realize the overall output of database content rather than one-to-one output. It will continue to be improved when the work is not busy in the later stage. Change the views of home3
# Content page def home3(request): from blog.models import Content blog_list = Content.objects.all() # Get all data return render(request, 'home3.html', {'blog_list': blog_list})
11.urls does not need to be modified, home3 html
<!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>details</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> </head> <body style="background-image: url({% static 'images/hd3.jpg' %});background-size:100%;" > <div class="container"> <ol class="breadcrumb my-4"> <li class="breadcrumb-item active">content</li> </ol> <table class="table"> <thead class="thead-dark"> <tr> <th>theme</th> <th>content</th> </tr> </thead> <tbody> </tbody> {% for blog in blog_list %} <tr> <td> {{ blog.topic }} </td> <td class="align-middle">{{ blog.details }}</td> </tr> {% endfor %} </tbody> </table> </div> </body> </html>
12. I finally finished writing. During this period, I felt that my basic knowledge was weak. During this period, I encountered various problems, including fishing at work, writing code, html language, and all kinds of difficult and miscellaneous diseases, but they were solved one by one. I still need to write @ login according to the teacher's requirements_ Required, because they are all background admin s, so they don't write. They have learned a lot in the process. In the next step, they will continue to study and finish their studies seriously. Finally, the overall effect is attached: