Python是一種流行的程式語言,具有簡單易學、可讀性高和廣泛應用等優點,Python被廣泛應用於Web開發、資料科學、機器學習等領域。其中,Django是高階Web框架,基於Python語言開發,是Web應用程式開發的重要工具。
Django的特點是易於學習、易於維護、遵循MVC模式、自帶ORM等優點,因此受到開發者們的歡迎。本文將介紹使用Python和Django建立Web應用程式的實用指南。
- 安裝Python和Django
首先,我們需要安裝Python和Django。可以從Python官方網站(www.python.org)下載最新的Python安裝包,安裝後,可以在命令列中輸入python,檢查Python是否正確安裝。
安裝Django可以透過pip套件管理器進行安裝,打開命令列窗口,輸入以下命令:
pip install django
安裝完成後,可以透過以下命令檢查Django是否正確安裝:
django-admin --version
如果傳回Django版本號,則表示安裝成功。
- 建立Django專案
在命令列中進入要儲存Django專案的目錄,然後輸入以下指令:
django-admin startproject myproject
這個指令將會建立一個名為「myproject」的Django項目,專案目錄結構如下:
myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py
其中,manage.py是腳本文件,用於在命令列中執行Django任務;settings.py包含項目的設定;urls. py包含專案的URL模式;wsgi.py指定Web伺服器將請求轉送到哪個Python應用程式。
- 建立Django應用程式
在Django專案中,應用程式是指將Web應用程式與特定業務邏輯結合的元件。我們可以使用以下命令在已創建的Django專案中創建應用程式:
python manage.py startapp myapp
這個命令將在Django專案中的“myproject”目錄中創建一個名為“myapp”的應用程序,應用程式目錄結構如下:
myapp/ __init__.py admin.py apps.py models.py tests.py views.py
其中,models.py包含應用程式的資料庫模型定義;views.py包含請求處理函數;admin.py用於管理後台;tests.py包含應用程式的測試程式碼。
- 寫Django模型
Django的ORM是一個將Python類別對應到資料庫表的工具,我們可以透過編輯models.py檔案來定義應用程式的模型。
例如,我們建立一個名為「Book」(書籍)的模型,它包含以下屬性:
- title(書名):字串類型,最大長度為200字元
- author(作者):字串類型,最大長度為50個字元
- pub_date(出版日期):日期類型
- price(價格):十進位類型,最大值為9999.99,小數位為2位元
程式碼如下:
from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=50) pub_date = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2, max_value=9999.99)
- 建立資料庫表
在Django中,資料庫表是透過模型自動建立的。我們可以使用以下命令將模型創建到資料庫中:
python manage.py makemigrations myapp
這個命令將創建一個資料庫遷移文件,描述如何將模型映射到資料庫表中。我們可以使用以下指令將遷移套用至資料庫:
python manage.py migrate
這個指令會依照遷移檔案中的指令,將表格建立到資料庫中。
- 編寫檢視
在Django中,檢視是請求處理函數,負責處理使用者發起的請求,並產生回應內容。在編寫視圖之前,我們需要設定URL模式,將請求與視圖關聯起來。我們可以編輯urls.py文件,加入以下程式碼:
from django.urls import path from . import views urlpatterns = [ path('books/', views.book_list, name='book_list'), path('books/new', views.book_new, name='book_new'), path('books/<int:pk>/edit/', views.book_edit, name='book_edit'), path('books/<int:pk>/delete/', views.book_delete, name='book_delete'), ]
這個程式碼片段定義了4個URL模式,分別與4個視圖關聯起來。其中,path函數的第一個參數指定URL,第二個參數指定視圖函數,第三個參數是模板引擎將視圖渲染成HTML時的名稱。
在views.py檔案中,我們可以定義請求處理函數,例如:
from django.shortcuts import render, get_object_or_404 from .models import Book from .forms import BookForm def book_list(request): books = Book.objects.all() return render(request, 'book_list.html', {'books': books}) def book_new(request): if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.save() return redirect('book_list') else: form = BookForm() return render(request, 'book_edit.html', {'form': form}) def book_edit(request, pk): book = get_object_or_404(Book, pk=pk) if request.method == "POST": form = BookForm(request.POST, instance=book) if form.is_valid(): book = form.save(commit=False) book.save() return redirect('book_list') else: form = BookForm(instance=book) return render(request, 'book_edit.html', {'form': form}) def book_delete(request, pk): book = get_object_or_404(Book, pk=pk) book.delete() return redirect('book_list')
#其中,book_list函數用於傳回所有圖書清單;book_new函數用於建立新的圖書;book_edit函數用於編輯已有的圖書;book_delete函數用於刪除圖書。
- 編寫HTML模板
在Django中,我們可以使用模板引擎來將視圖函數渲染成HTML頁面,從而為使用者呈現可視化的Web介面。我們可以在templates目錄下,建立一個HTML模板文件,例如book_list.html。
程式碼如下:
{% extends 'base.html' %} {% block content %} <h1 id="Books">Books</h1> <a href="{% url 'book_new' %}">New book</a> <table> <thead> <tr> <th>Title</th> <th>Author</th> <th>Pub date</th> <th>Price</th> <th>Actions</th> </tr> </thead> <tbody> {% for book in books %} <tr> <td>{{ book.title }}</td> <td>{{ book.author }}</td> <td>{{ book.pub_date }}</td> <td>{{ book.price }}</td> <td> <a href="{% url 'book_edit' book.id %}">Edit</a> <a href="{% url 'book_delete' book.id %}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> {% endblock %}
其中,{% extends 'base.html' %}指定此範本繼承自base.html範本;{% block content %}至{% endblock %}指定這個模板中的主要內容是包含在其中的內容。
我們執行Django伺服器,並在瀏覽器中開啟localhost:8000/books/,即可查看所有書籍清單。
透過這個簡單的範例,我們了解到如何使用Python和Django建立Web應用程序,並涉及了基本的操作,包括安裝Python和Django,創建Django專案和應用程序,編寫Django模型、視圖和模板。希望這個指南可以幫助您建立自己的Web應用程式。
以上是使用Python和Django建立Web應用程式:一個實用的指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Dreamweaver CS6
視覺化網頁開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。