首頁 > 後端開發 > Python教學 > 解鎖姜戈:初學者&# 生成點

解鎖姜戈:初學者&# 生成點

WBOY
發布: 2024-08-14 10:42:30
原創
660 人瀏覽過

Django Unlocked: Beginners

簡介

Django 是一個強大的 Web 框架,可讓您快速且有效率地建立健壯、可擴展的 Web 應用程式。它是用 Python 編寫的,遵循「包含電池」 理念,這意味著它具有許多內建功能,可以使開發更快、更輕鬆,從而適合原型設計。 無論您是創建小型個人專案還是大型企業應用程序,Django 都有您需要的工具。

在本指南中,我將引導您了解Django 的MVT 設計模式(模型、視圖和模板),為建立您自己的Web 應用程式提供堅實的基礎。最後,您將清楚地了解 Django 的工作原理以及如何有效地使用其元件。

使用虛擬環境設定 Django 專案

參考Django的官方文件:Django Documentation

在深入研究核心元件之前,讓我們先設定一個虛擬環境來管理專案的依賴項。這有助於保持您的專案隔離並防止與其他 Python 專案發生衝突。

注意:我強烈鼓勵使用Linux。如果您使用的是Windows,請安裝WSL以存取Linux環境。

1.安裝venv模組:

sudo apt install python3-venv
登入後複製

2. 建立虛擬環境:

python -m venv .venv
登入後複製

3.激活虛擬環境:

source .venv/bin/activate
登入後複製

4.安裝Django:

啟動虛擬環境後,安裝Django:

python -m pip install django
登入後複製

5.創建Django專案:

django-admin startproject myproj
登入後複製

將 myproj 替換為您想要的項目名稱。

6. 建立應用程式:

在您的專案目錄中,建立一個應用程式。

python manage.py startapp myapp
登入後複製

7. 將新建立的應用程式新增至位於以下位置的settings.py:

您的專案名稱/您的專案名稱/settings.py

INSTALLED_APPS = [
    'myapp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
登入後複製

您的專案現在已經設定了基本結構,包括管理.py 檔案、專案設定和您的第一個應用程式

模型

模型 使用 Python 類別定義資料庫表的結構以及它們之間的關係。每個模型類別對應到一個資料庫表,模型的每個屬性對應一個資料庫欄位。 Django 允許您使用繼承自 django.db.models.Model 的類別來定義資料庫模式,從而簡化了此過程。

ORM 代表物件關係映射。在 Django 中,ORM 是一個強大的功能,它允許開發人員使用 Python 程式碼而不是編寫 SQL 查詢來與資料庫互動。此抽象層將 Python 類別(模型)對應到資料庫表,並將這些類別的實例對應到表中的行。

介紹SQLite

Django 使用 SQLite 作為預設資料庫,因為它非常容易設定。 SQLite 是一種輕量級資料庫,它將所有資料保存在一個簡單的檔案中,因此您無需安裝任何額外的內容即可開始儲存和管理網站的資料。這使其成為開發和測試的絕佳選擇,因為它使您可以專注於建立應用程序,而不必擔心複雜的資料庫設定。

在 Django 中,一個名為 Airport 的表,具有「code」和「city」等屬性,被表示為一個 Python 類,其中每個屬性都定義為一個類變數。

class Airport(models.Model):
    code = models.CharField(max_length=3)
    city = models.CharField(max_length=64)
登入後複製

1. 定義模型:

在應用程式的 models.py 中,使用 Django 的 ORM 定義模型。

from django.db import models

class Flight(models.Model):
    # Diri, kada flight naa tay origin kung asa gikan, destination, ug duration
    # Nakabutang sa parameters ilang properties, such as length of the characters

    origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='departures')
    destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name='arrivals')
    duration = models.IntegerField()

    def __str__(self):
        return f'{self.id}: {self.origin} to {self.destination} | {self.duration} minutes.'
登入後複製

2. 遷移:

定義模型後,建立並套用遷移以更新資料庫架構。

簡單來說:

  • makemigrations 就像規劃您想要對資料庫進行的變更。
  • migrate 實際上是在資料庫上執行這些變更。因此,在使用 makemigrations 進行規劃後,遷移就是執行並套用變更的時間。
python manage.py makemigrations
python manage.py migrate
登入後複製

3. 與模型互動:

使用 Django 的 shell 與您的模型互動:python manage.py shell

範例:

>> from flights.models import Flight

>> flight1 = Flight(origin="Davao", destination="Manila", duration=569)
>> fligh1.save()
登入後複製

我建立了 Flights 模型的一個實例。此實例 Flight1 代表我的資料庫的 Flight 表中的一行。 Flight 模型中定義了出發地、目的地和持續時間欄位。
當您建立實例時。您正在將這些欄位設定為特定值:

  • origin : "Davao"
  • destination : "Manila"
  • duration : 569 (representing the flight duration in minutes)

Views

Views are a crucial part of the framework that handles the logic behind what a user sees and interacts with in a web application. Views are responsible for processing user requests, retrieving necessary data from the database, and returning the appropriate response (typically an HTML page, JSON data, or a redirect).

In simple terms, Views in Django act as the middleman between the web pages and the data. They take requests from users, process any necessary data, and then send back the appropriate response, like a webpage or a file. Essentially, views decide what content should be shown to the user and how it should be presented.

In this read, we will only be using Function-Based Views

1. Function-Based Views:

These are Python functions that take a web request and return a web response. The most basic view in Django is a function that receives a request object and returns a response object.

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, World!")
登入後複製

2. Class-Based Views:

These are Python classes that provide more structure and allow for more complex functionality compared to Function-Based Views.

from django.views import View
from django.http import HttpResponse

class MyView(View):
    def get(self, request):
        return HttpResponse("Hello, World!")
登入後複製

Templates

Templates are used to render HTML and display data to users. They allow you to separate your HTML from Python code. Django templates are a powerful tool for generating dynamic HTML content in your web application. By separating the presentation (HTML) from the backend logic (Python code), templates help keep your code clean, maintainable, and reusable.

In simple terms, Templates in Django are like blueprints that define how data should be displayed on a webpage. They allow you to combine static content (like HTML) with dynamic content (like data from a database) to create a fully rendered page. Instead of hardcoding every detail, you use templates to keep the design and data separate, making it easier to update and manage your website.

1. Creating a Template

Start with creating a directory for your templates inside your app and name the directory as templates. Create another directory inside the templates named myapp.

django-proj/myapp/templates/myapp
登入後複製

Now, you can finally place all your templates inside the inner directory you created:

django-proj/myapp/templates/myapp/base.html
登入後複製

Creating the base.html allows you to define a base template or layout with common structure (headers, navbar, and footer) that other templates can inherit. This feature is useful for maintaining consistency across different pages.

Example:

<!DOCTYPE html>
<html>
<head>
    <title> {% block title %} myApp {% endblock %} </title>
</head>
<body>
    <header>
        <h1>My Site</h1>
    </header>
    <div class="content">
        {% block content %}{% endblock %}
    </div>
    <footer>
        <p>Footer content here</p>
    </footer>
</body>
</html>
登入後複製

Let's create another template called index.html and place it in the same directory of base.html.

Example of extending template index.html:

{% extends "myapp/base.html" %}
{% block content %}
    <h1>Flights</h1>
    <ul>
        {% for flight in flights %}
            <li>Flight: {{ flight.id }} {{ flight.origin }} to {{ flight.destination }}</li>
        {% endfor %}
    </ul>
{% endblock %}
登入後複製

The {% extends "myapp/base.html" %} tells Django to use the base.html as the base layout template. The {% block content %} defines a block of content that will be filled with content from index.html. The content block in base.html will be replaced with the content provided in index.html.

2. Rendering Templates

In a Django view, you typically render a template using the render() function, which combines the template with the context data to produce the final HTML output.

from django.shortcuts import render

def index(request):
    return render(request, 'myapp/index.html')
登入後複製

When Django renders index.html, it will include the structure from base.html, replacing the content block with the content specified in index.html. This allows for consistent design across pages and makes it easy to update the overall layout without changing every individual template.

URLs and Routing

Django uses URL patterns to map URLs to views. These patterns are defined in a file called urls.py within each Django app.

URL patterns are defined with the path() function, mapping specific URL paths to view functions or classes. Dynamic URL segments, such as , allow for capturing variables from the URL to be used in views. The include() function enables modular URL management by including patterns from other apps.

In simple terms, URLs are like street addresses for different pages on your website. Routing is the system that makes sure when someone types in a specific address (URL), they get directed to the right page. You set up these "addresses" in a special file so Django knows where to send people when they visit your site.

1. Configuring URLs:
Define URL patterns in urls.py of your app:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]
登入後複製

Inlcude your app's URLs in the project's urls.py:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls'))
]
登入後複製

Wrapping up

Congratulations! You've taken the first steps in learning Django. I’ve covered the basics of Models, Views, Templates, and URL routing. With these fundamentals, you’re on your way to building your own Django applications. Keep experimenting, keep coding, and don't hesitate to dive deeper into the Django documentation and community resources.

I hope this guide has made these concepts clearer and that you’ve learned something valuable along the way.

  • 0xshr00msz

以上是解鎖姜戈:初學者&# 生成點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板