1
1

新人エンジニアのDjango挑戦:Django開発の基礎知識

Posted at

はじめに

Djangoは、Pythonで開発される強力なWebフレームワークで、多くのプロジェクトで利用されています。この記事では、新人エンジニアがDjangoを使ってWebアプリケーションを開発するための基本的なステップを紹介します。

まず、Djangoの導入から始めます。Pythonとpipのインストールを確認し、Djangoのセットアップ方法を詳しく説明します。その後、Djangoの基本的な機能を利用して簡単なWebアプリケーションを構築します。具体的には、モデル、ビュー、テンプレートを使ってデータベース操作やページ表示を実装する方法を解説します。

実装(Ubuntu)

仮想環境の作成

参考

pythonで独立した仮想環境を作製することで、異なるプロジェクトがお互いに影響を与えないようにします。
今回は、venvで仮想環境を作成します。

python3 -m venv django
source django/bin/activate

上記のコマンドでdjangoという名前の仮想環境を作製し、仮想環境をアクティベートします。

必要モジュールのインストール

djangoに必要なpythonモジュールをinstallします。
今回は、以下のモジュールをinstallしました。

asgiref==3.8.1
Django==5.0.7
numpy==2.0.0
packaging==24.1
pandas==2.2.2
plotly==5.22.0
psycopg==3.2.1
psycopg2==2.9.9
python-dateutil==2.9.0.post0
pytz==2024.1
six==1.16.0
sqlparse==0.5.0
tenacity==8.5.0
typing_extensions==4.12.2
tzdata==2024.1

install方法

  1. requirements.txtを作製して、上記の内容をコピー&ペーストします
  2. pip install -r requirements.txtで、仮想環境にバージョンを指定したモジュールをinstallできます

Djangoプロジェクトの作成

Djangoのプロジェクトとは

Djangoのプロジェクトは、Webアプリケーションを効率的に開発するためのフレームワークと構造を提供します。各ディレクトリとファイルは特定の役割を持っており、これらを組み合わせることで強力でスケーラブルなWebアプリケーションを構築することができます。

Djangoのプロジェクト作成

django-admin startproject mysite

上記のコマンドでmysiteというプロジェクトを作製できます。
上記のコマンドで以下のようなファイルが作成されます。

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py

Djangoアプリの起動

python manage.py runserver

上記のコマンドで開発サーバーが立ち上がります。
ブラウザで http://127.0.0.1:8000/ にアクセスしてみてください。 "Congratulations!" と表示された、ロケットが離陸しているページが出るはずです。

アプリケーションの作成

python manage.py startapp test_django

上記のコマンドでアプリを作製されます。
test_djangoというディレクトリが作成されます。

test_django/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py

ここまでで、djangoアプリの作成の準備が完了です。

DBの作成

ubuntsuにdockerをinstall

postgresを利用するために、dockerをinstallする。
以下のサイトを参考にinstallしました。

参考

docker-composeファイルの作成

docker-compose.ymlを作製。
ファイル内には以下の内容を記載する

version: '3.8'

services:
  db:
    image: postgres:13
    container_name: my_postgres
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: mydatabase
    ports:
      - "5432:5432"
    volumes:
      - db_data:/var/lib/postgresql/data

volumes:
  db_data:

DBの起動

docker compose up -d

上記のコマンドをdocker-compose.ymlと同じディレクトリ内で実行すると、DBが立ち上がる。

プロジェクトにDBの設定追加

settings.pyにpostgresへ接続する設定を追加する。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': '0.0.0.0',
        'PORT': '5432',
    }
}

モデルの作成

test_django/models.pyにDBのモデルを追加する。

from django.db import models

# Create your models here.
class Spotify(models.Model):
    id = models.BigAutoField(primary_key=True)
    spotify_id = models.CharField(max_length=220)
    name = models.CharField(max_length=200)
    genre = models.CharField(max_length=200)
    artists = models.CharField(max_length=200)
    album = models.CharField(max_length=200)
    popularity = models.IntegerField()
    duration_ms = models.IntegerField()
    explicit = models.BooleanField()

上記は、以下のkaggleのサンプルデータを参考にDBのテーブルカラムの設定しました。

テーブルの作成・更新

python manage.py makemigrations
python manage.py migrate

上記のコマンドで、DBのテーブルが作成されます。
上記のコマンドは、モデルを編集されるたびに、上記のコマンドを実行して、DBの情報を更新します。

View層

今回は、djangoのアプリで以下のような3ページを作製します。

  1. view層で作成されたデータをヒストグラム表示
  2. DBのデータをテーブル表示
  3. DBのデータヒストグラム表示

test_django/views.pyの内容を以下のように編集する。

from django.shortcuts import render
from django.http import HttpResponse
import plotly.express as px
import plotly.graph_objects as go
from test_django.models import Spotify

# Create your views here.
def index(request):
    
    # データを用意
    data = {
        'x': [1, 2, 3, 4, 5],
        'y': [10, 11, 12, 13, 14]
    }

    # Plotlyでグラフを作成
    fig = px.line(data, x='x', y='y', title='Sample Plot')
    
    # グラフをHTMLに変換
    graph = fig.to_html(full_html=False)

    return render(request, 'sample1.html', {'graph': graph})

def table(request):
    test = Spotify.objects.all()
    return render(request, 'db_table.html', {'test': test})

def make_graphe(request):
    test = Spotify.objects.values("popularity")
    data = list(test)
    
    fig = px.histogram(data, title='Histogram Example')
    graph = fig.to_html(full_html=False)
    
    return render(request, 'sample1.html', {'graph': graph})

templatesの作成

test_django/templatesのディレクトリを作成する。

グラフを表示するtempplateの作成

test_django/templates/sample1.htmlに以下の内容を作製

<h1>sample django</h1>

<div>
    {{ graph|safe }}
</div>


テーブルを表示するtemplateの作成

test_django/templates/db_table.htmlを以下の内容で作成。

<h1>DB django table</h1>

<body>
    <h1>table List</h1>
    <table border="1">
        <tr>
            <th>name</th>
            <th>album</th>
            <th>popularity</th>
            <th>duration_ms</th>
            <th>explicit</th>
        </tr>
        {% for t1 in test %}
        <tr>
            <td>{{ t1.name }}</td>
            <td>{{ t1.album }}</td>
            <td>{{ t1.popularity }}</td>
            <td>{{ t1.duration_ms }}</td>
            <td>{{ t1.explicit }}</td>
        </tr>
        {% endfor %}
    </table>
</body>


urlの設定

mysite/urls.pyに各ページの設定を記載する。

from django.contrib import admin
from django.urls import path
from test_django import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('db-table/', views.table, name='db-table'),
    path('make-graphe/', views.make_graphe, name='make-graphe'),
]

DBにcsvデータを投入

data/spotify_tracks.csvに今回利用するデータをDBに投入する。
以下のpythonプログラムでdata/spotify_tracks.csvにあるデータをDBに投入できる。

# import_books.py

import csv
import os
import django

# Djangoプロジェクトの設定を読み込む
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

from test_django.models import Spotify

def import_books_from_csv(file_path):
    Spotify.objects.all().delete()
    with open(file_path, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            Spotify.objects.create(
                spotify_id=row['id'],
                name=row['name'],
                genre=row['genre'],
                artists=row['artists'],
                album=row['album'],
                popularity=row['popularity'],
                duration_ms=row['duration_ms'],
                explicit=row['explicit']
            )
    print("Data imported successfully")

if __name__ == "__main__":
    import_books_from_csv('data/spotify_tracks.csv')

少量のデータの場合は以下のコマンドでデータを投入できる。

python manage.py loaddata initial_data.json

initial_data.jsonの中身は以下のようなデータ
JSONやXML、YAMLファイルの形式でデータを投入可能。
csvでデータを投入する場合は、上記のpythonコードでデータ投入するほうがよさそう…
※csvをより簡単にテーブル投入できる方法は未調査

[
    {
        "model": "myapp.mymodel",
        "pk": 1,
        "fields": {
            "field1": "value1",
            "field2": "value2"
        }
    },
    {
        "model": "myapp.mymodel",
        "pk": 2,
        "fields": {
            "field1": "value3",
            "field2": "value4"
        }
    }
]

djangoアプリの起動

python manage.py runserver

ヒストグラムの表示

django起動中に上記のURLにアクセスする。
image.png

テーブル表示

image.png

view層で作成したデータの表示

image.png

まとめ

Djangoの基本的な機能を新人エンジニアが試してみた結果、多くの学びがありました。Djangoは強力で柔軟なWebフレームワークであり、特にDB接続が非常に簡単に行える点が印象的でした。しかし、Django独特のルールや構造に慣れるまでには時間がかかることも実感しました。

初期の構築はベテランエンジニアが担当し、開発ルールがしっかりと定まってから若手エンジニアが開発を進める方が、プロジェクト全体の効率や品質を向上させるために適していると感じました。これにより、新人エンジニアも安心して開発に取り組むことができ、スムーズにプロジェクトを進めることができます。

Djangoを使った開発は、新人エンジニアにとっても貴重な経験となり、スキルアップにつながることを実感しました。これからも継続的にDjangoを学び、より高度な機能やプロジェクト管理にも挑戦していきたいと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1