程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[introduction to Django] using Django to develop projects (Continued)

編輯:Python

Reference material :《Python Programming : From introduction to practice 》——【 beautiful 】Eric Matthes Writing Translated by Yuan Guozhong

Python edition :3.9.5

django edition :3.2.6

System :Windows 10

List of articles

    • 3. Create home page
      • 3.1 mapping URL
      • 3.2 Authoring views
      • 3.3 Write templates
    • 4. Create other pages
      • 4.1 Template inheritance
        • 1. The parent template
        • 2. Sub template
      • 4.2 Show all smiling hosts
        • 1. URL Pattern
        • 2. View
        • 3. Templates
      • 4.3 A page showing the cause of a particular laugh
        • 1. URL Pattern
        • 2. View
        • 3. Templates
        • 4. Set each entry in the page that shows all laughing hosts as a link


Last one Recorded in Build project Create application The detailed process of these two steps , This article will record the detailed process of the next two steps —— Create home page and Create other pages .

Let's start !


3. Create home page

Use Django The process of creating a web page is usually divided into three stages : Definition URL 、 Write views and templates . First , you Must define URL Pattern .URL The pattern describes URL How it was designed , Give Way Django Know how to connect browser requests to websites URL matching , To determine which page to return .

Every URL Are mapped to specific views —— The view function obtains and processes the data required by the web page . View functions usually Call a template , The latter generates web pages that the browser can understand .

3.1 mapping URL

The user enters... In the browser URL And click a link to request a web page , So we need to determine what the project needs URL. Current foundation URL(http://127.0.0.1:8000/) Return to the default Django Website , Let us know that the project has been set up correctly . We will revise this point , Put this foundation URL Map to our project hahaproject The home page of .

Current project home folder hahaproject Documents in urls.py It has the following contents :

urls.py

"""hahaproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]

The first line of the document string gives the description of the file :hahaproject URL Configuration. The main part of urlpatterns It's the point —— In this For the whole project Of urls.py In file , Variable urlpatterns That contains the applications in the project URL. The only existing at present URLadmin.site.urls, This module defines all that can be requested in the admin site URL.

below , We need to include our own applications hahaprojects Of URL 了 :

urls.py

"""hahaproject URL Configuration"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('hahaprojects.urls', 'hahaprojects'), namespace='hahaprojects')),
]

A new line of code added to the list contains the application hahaprojects Of URL The code of . About path Function and include() The use of the function can be referred to Official documents . Don't forget it include() The first argument to the function is a binary group , Which should give app_namespace, If you don't give it, you will report an error .

All in all , The purpose of this line of code is : When we ask the foundation URL when , Would call include() function , The function will contain the application hahaprojects Module in hahaprojects.urls. The current folder hahaprojects Also there is no urls.py, therefore , Let's create this urls.py.

In the application hahaprojects Folder hahaprojects Created in urls Of .py file , The contents are as follows :

urls.py

""" Definition hahaprojects Of URL Pattern """
from django.urls import path
from . import views
urlpatterns = [
# Home page 
path('', views.index, name='index'),
]

path() The first argument to the function is the base URL hinder URL, And this is an empty string , therefore It corresponds to the foundation URL. The second parameter specifies the view function to call . The third parameter sets this URL The name of the schema is specified as index, Let's reference it elsewhere in the code . Whenever you need to provide a link to this home page , We will all use this name , Without having to write it again URL. So in general , When we ask the foundation URL when ,Django Will call views.index, This is a view function , Write later .

3.2 Authoring views

The view function accepts the information in the request , Prepare the data needed to generate the web page , Then send the data to the browser —— This is usually achieved using a template that defines what a web page is like .

hahaprojects Documents in views.py It's the execution of orders python manage.py startapp Automatically generated when , There is only one line import Statement and a line of comments , Here we define index function , The modified code is as follows :

views.py

from django.shortcuts import render
def index(request):
""" The home page of the project """
return render(request, 'hahaprojects/index.html')

render() function Render the response based on the data provided by the view .URL When the request matches the pattern we just defined ,Django Will be in the file views.py Find the function index(), Again Pass the request object to the view function .

3.3 Write templates

The template defines the structure of the web page . The template specifies what the web page looks like , and Whenever a web page is requested ,Django Relevant data will be filled in . Templates let you Be able to access any data provided by the view . Our home page view does not provide any data , So the corresponding template is very simple .

Now we need to create index.html This template . The created location requires some special processing —— We started with hahaprojects Created in templates Folder , Then create a file named hahaprojects Folder , This folder is where the template is created . We create files index.html, Then write the following code :

index.html

<p>HahaProject</p>
<p>
HahaProject Help you record the laughter around you ( Don't think it's useless Project, Because we just use it to learn ).
</p>

Now there are three steps ——** Definition URL( Write... In the home folder urls.py And add... To the application urls.py) 、 Authoring views ( To write views.py) And writing templates ( To write .html file )** It's all done , Next, enter the base... In the browser URLhttp://127.0.0.1:8000, You'll see the following interface :

you 're right , What is shown here is what we wrote index.html The content in .

The process of creating a web page can seem complicated , But will URL、 The effect of separating the view from the template is actually very good . This allows us to consider different aspects of the project separately , And when the project is large , Allow participants to focus on what they do best .

4. Create other pages

By creating the home page, we are familiar with the process of creating web pages , Let's expand our hahaproject project . We will create two web pages that display data , A host used to show laughter , Another shows several reasons for laughter ( One to many relationship ). For each page , We will all designate URL Pattern , Write a view function , And write a template . But because most templates have the same parts , So we need to use template inheritance , That is, create a parent template first , Other templates in the project will inherit it .

4.1 Template inheritance

Writing a parent template that contains common elements makes it much easier to modify the overall appearance of the project .

1. The parent template

stay index.html Create a directory named base.html The template of . This file contains elements that are common to all pages ; Other templates inherit base.html. Since we will include this template in each page , So we set the title as a link to the home page :

base.html

<p>
<a href="{% url 'hahaprojects:index' %}">HahaProject</a>
</p>
{% block content %}{% endblock content %}

The second line is actually a hyperlink , But we didn't give the address of the link directly URL, It uses a Template tags To generate , It uses curly braces and a percent sign {% %} It means . The template tag is a short piece of code , Generate information to be displayed in the web page . ad locum , Generated URL And hahaprojects/urls.py The name defined in is index Of URL Pattern matching .hahaprojects It's a namespace, and index It's time to namespace A unique URL Pattern ( This is the same as the two urls.py Echo each other ).

At the end is a pair of inserted block labels , This block is called content, It's a place holder , The information contained will be specified by the sub template .

2. Sub template

Now you need to rewrite index.html, To inherit base.html, As shown below :

index.html

{% extends "hahaprojects/base.html" %}
{% block content %}
<p>HahaProject</p>
<p>
HahaProject Help you record the laughter around you ( Don't think it's useless Project, Because we just use it to learn ).
</p>
{% endblock content %}

The first line is the inheritance statement , Give Way Django Know which parent template it inherits . The next thing is {% block content %} and {endblock content}, What is filled between the two is the unique content of the current web page .

4.2 Show all smiling hosts

This page will display the owners of all smiles stored in the current database , It requires the use of data , Let's start writing !

The writing steps are still three —— Definition URL、 Authoring views 、 Write templates .

1. URL Pattern

Usually , Use a simple URL Fragment to indicate the information displayed on the web page ; We will use the word laughters, therefore URLhttp://127.0.0.1:8000/laughters It will return to the page showing all the smiling hosts . Next, modify the application hahaprojects Medium urls.py file :

urls.py

""" Definition hahaprojects Of URL Pattern """
from django.urls import path
from . import views
urlpatterns = [
# Home page 
path('', views.index, name='index'),
# Show all smiling hosts 
path('laughters/', views.laughters, name='laughters'),
]

We are on the list urlpatterns Another line of statements has been added to the , Its URL All requests that match this pattern will be passed to views.py The function in laughters() To deal with . And now we have views.py Add this function to the .

2. View

function laughters You need to get some data from the database , And send it to the template . So we need to models.py Import class ( The model ), And then in the definition of laughters() Use it in the function . The modified views.py The documents are as follows :

views.py

from django.shortcuts import render
from .models import Laughter
def index(request):
""" The home page of the project """
return render(request, 'hahaprojects/index.html')
def laughters(request):
""" Show all the laughing masters """
laughters = Laughter.objects.order_by('date_added')
context = {
'laughters': laughters}
return render(request, 'hahaprojects/laughters.html', context)

The first 2 OK, we imported the class Laughter, Then we define the function laughters(). In this function , We call order_by Function pair class Laughter All instances of are in accordance with the properties date_added Sort , The returned query set is stored in laughters in , Then we define a to be sent to the template Context context, This is a dictionary , The key is the name of the data we will use to access in the template , The value is the data we want to send to the template . You can see , We'll change the variables context It's also passed on to render() function . The next thing to do is to write laughters.html.

3. Templates

stay index.html Create a folder named laughters Of .html file , Write it below :

laughters.html

{% extends "hahaprojects/base.html" %}
{% block content %}
<p>Owners of Laughter</p>
<ul>
{% for laughter in laughters %}
<li>{
{ laughter }}</li>
{% empty %}
<li>No laughters have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}

Here we use an equivalent of for Circular template label , It traverses the dictionary context List in laughters. This is not the standard HTML grammar , It's for Django Read the . The end result is an unordered list , Every entry is a list laughters The elements in .

Next we need to modify the parent template , Make it include a link to the page that shows all laughing hosts :

base.html

<p>
<a href="{% url 'hahaprojects:index' %}">HahaProject</a> -
<a href="{% url 'hahaprojects:laughters' %}">Owners of Laughter</a>
</p>
{% block content %}{% endblock content %}

We added a line of hyperlinks ,URL Still use template tags to generate , It generates links with hahaprojects/urls.py Middle name is laughters Of URL Pattern matching .

Now let's refresh the home page in the browser , You can see the interface below :

We see two hyperlinks at the beginning , The first is a link to the home page , The second is a page that links to all laughing hosts .

4.3 A page showing the cause of a particular laugh

Let's create a page that shows several reasons for a particular laugh . Or the three steps , Definition URL, Authoring views , Write templates . At the same time, we will also modify the laughters.html, Make every item a link , Link to this page for specific reasons for laughing . Let's start !

1. URL Pattern

The page that shows the reason for a particular laugh is the same as all the previous pages URL The patterns are slightly different , Because it will use laughter Of id Property to indicate which smile is requested . for example URLhttp://http://127.0.0.1:8000/laughters/1/ It should correspond to id by 1 The detailed page of smile . The following is related to this URL Matching patterns , It is contained in hahaprojects/urls.py in , The revised document is as follows :

urls.py

""" Definition hahaprojects Of URL Pattern """
from django.urls import path
from . import views
urlpatterns = [
# Home page 
path('', views.index, name='index'),
# Show all smiling hosts 
path('laughters/', views.laughters, name='laughters'),
# Specific reasons for laughter 
path('laughters/<int:laughter_id>/', views.laughter, name='laughter'),
]

We are on the list urlpatterns I added another one to the URL, among /<int:laughter_id>/ Matches an integer contained within two slashes , And store this integer in a file named laughter_id In the arguments of . If URL Match this pattern , that Django The view function... Will be called laughter(), And will be stored in laughter_id The value in is passed to it as an argument . In this function , We will use laughter_id To get the corresponding topic .

2. View

function laughter() You need to get the owner of the specified smile and all the reasons associated with it from the database , As shown below :

views.py

from django.shortcuts import render
from .models import Laughter
def index(request):
""" The home page of the project """
return render(request, 'hahaprojects/index.html')
def laughters(request):
""" Show all the laughing masters """
laughters = Laughter.objects.order_by('date_added')
context = {
'laughters': laughters}
return render(request, 'hahaprojects/laughters.html', context)
def laughter(request, laughter_id):
""" Show the owner of a single smile and all the reasons for it """
laughter = Laughter.objects.get(id=laughter_id)
laugh_reasons = laughter.laughreason_set.order_by('-date_added')
context = {
'laughter': laughter, 'laugh_reasons': laugh_reasons}
return render(request, 'hahaprojects/laughter.html', context)

This view function contains request Object also contains another formal parameter . stay laughter() Function , We use get() To get the specified smile . And then we use .laughreason_set To get the entry associated with this laugh , And press them date_added Descending order (- Specifies to arrange in descending order ). then laughter and laugh_reason Are stored in the dictionary context in , Then send the dictionary to the template laughter.html. Let's write this template .

3. Templates

This template needs to show the owner of the smile and several reasons for it ; If the current smile does not contain any reason , We also need to point out that .

laughter.html

{% extends "hahaprojects/base.html" %}
{% block content %}
<p><b>Owner of Laughter:</b> {
{ laughter }}</p>
<p><b>Reasons of laughing:</b></p>
<ul>
{% for laugh_reason in laugh_reasons %}
<li>
<p>{
{ laugh_reason.date_added|date:'M d, Y H:i' }}</p>
<p>{
{ laugh_reason.reason|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no reasons for this laughter yet.
</li>
{% endfor %}
</ul>
{% endblock content %}

The first 10 That's ok ,| Represents a template filter , That is, the function that modifies the value of the template variable . filter date:'M d, Y H:i' Display the timestamp in such a format :January 1, 2021 00:00. The filter in the next line linebreaks Convert long entries containing line breaks into a format that browsers can understand , To avoid being displayed as an uninterrupted block of text .

4. Set each entry in the page that shows all laughing hosts as a link

Let's modify laughters.html, Let each of these items link to the corresponding web page :

laughters.html

{% extends "hahaprojects/base.html" %}
{% block content %}
<p>Owners of Laughter</p>
<ul>
{% for laughter in laughters %}
<li>
<a href="{% url 'hahaprojects:laughter' laughter.id %}">{
{ laughter }}</a>
</li>
{% empty %}
<li>No laughters have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}

We use template tags url according to hahaprojects Middle name is laughter Of URL Patterns to generate appropriate links . This URL Patterns need to provide arguments laughter_id, So we added attributes to the template tag laughter.id. Now every item in the list of every laughing host is a link , Link to the page showing the corresponding reason .

Now let's click on one of the entries , You can see the following interface :


Django This concludes the introductory section , We create Web Several important steps in the application —— Create project 、 Create application 、 Create a web page —— Learned how to use Django establish Web Applications . This is also for further study Django Laid the foundation .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved