Django ロック解除: 初心者&# スポーンポイント

WBOY
リリース: 2024-08-14 10:42:30
オリジナル
368 人が閲覧しました

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',
]
ログイン後にコピー

プロジェクトは、manage.py ファイル、プロジェクト設定、最初のアプリを含む基本構造でセットアップされました

モデル

モデル は、Python クラスを使用してデータベース テーブルの構造とテーブル間の関係を定義します。各モデル クラスは単一のデータベース テーブルにマップされ、モデルの各属性はデータベース フィールドに対応します。 Django は、django.db.models.Model.

から継承するクラスを使用してデータベース スキーマを定義できるようにすることで、このプロセスを簡素化します。

ORM は、オブジェクト リレーショナル マッピングの略です。 Django の ORM は、開発者が SQL クエリを作成する代わりに Python コードを使用してデータベースと対話できるようにする強力な機能です。この抽象化レイヤーは、Python クラス (モデル) をデータベース テーブルにマップし、それらのクラスのインスタンスをテーブル内の行にマップします。

SQLite の紹介

Django は、セットアップが非常に簡単であるため、SQLite をデフォルトのデータベースとして使用します。 SQLite は、すべてのデータを 1 つの単純なファイルに保存する軽量のデータベースであるため、Web サイトのデータの保存と管理を開始するために追加のものをインストールする必要はありません。これにより、複雑なデータベース設定を気にせずにアプリケーションの構築に集中できるため、開発やテストに最適です。

Django では、'code' や 'city' などの属性を持つ Airport という名前のテーブルは 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 は、データベースに加えたい変更を計画するようなものです。
  • 移行は実際にデータベース上でこれらの変更を実行します。したがって、makemigrations で計画を立てた後、変更を実行して適用するのが移行です。
python manage.py makemigrations
python manage.py migrate
ログイン後にコピー

3. モデルとの対話:

Django のシェルを使用してモデルを操作します: python manage.py シェル

例:

>> from flights.models import Flight

>> flight1 = Flight(origin="Davao", destination="Manila", duration=569)
>> fligh1.save()
ログイン後にコピー

Flights モデルのインスタンスを作成しました。このインスタンス Flight1 は、データベースの Flight テーブル内の 1 つの行を表します。フライト モデルには、出発地、目的地、期間のフィールドが定義されています。
インスタンスを作成するとき。これらのフィールドを特定の値に設定しています:

  • 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

以上がDjango ロック解除: 初心者&# スポーンポイントの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!