1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoで簡単Webアプリ開発入門

Posted at

はじめに

DjangoはPython製の人気Webフレームワークで、「管理画面」「認証」「ORM」など実用的な機能が標準装備されています。この記事では、Django未経験者でも1時間で動くWebアプリを作れることを目指し、環境構築からシンプルなアプリ作成までを丁寧に解説します。


1. Djangoのインストール

まずはDjangoをインストールしましょう。Pythonがインストールされていれば、コマンド1つでOKです。

pip install django

2. プロジェクトの作成

Djangoでは「プロジェクト」と「アプリ」という単位で開発します。まずはプロジェクトを作成しましょう。

django-admin startproject myproject
cd myproject

3. アプリの作成

次に、Webアプリの機能単位となる「アプリ」を作成します。ここでは「hello」というアプリを作ります。

python manage.py startapp hello

4. ビューの作成

hello/views.pyを編集し、Webページの表示内容を記述します。

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, Django!")

5. URLの設定

アプリのURLをプロジェクトに登録します。

1. アプリ側のURL設定

hello/urls.pyを新規作成し、以下を記述します。

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

2. プロジェクト側のURL設定

myproject/urls.pyを編集し、helloアプリへのルーティングを追加します。

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('hello.urls')),  # ここを追加
]

6. サーバーの起動と動作確認

開発用サーバーを起動します。

python manage.py runserver

ブラウザで http://127.0.0.1:8000/ にアクセスすると「Hello, Django!」と表示されれば成功です。


7. 管理画面を使ってみよう

Djangoの大きな特徴は「管理画面」。まずは管理ユーザーを作成します。

python manage.py createsuperuser

指示に従ってユーザー名・メール・パスワードを設定。

サーバー起動中に http://127.0.0.1:8000/admin/ にアクセスし、ログインすると管理画面が使えます。


8. テンプレート(HTML)の利用

HTMLファイルを使って、よりリッチなWebページも作れます。

1. テンプレートフォルダを作成

hello/templates/hello/index.html を作成し、以下のように記述します。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Hello Django</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
</html>

2. ビューを修正

hello/views.pyを以下のように変更します。

from django.shortcuts import render

def index(request):
    context = {'message': 'テンプレートからこんにちは!'}
    return render(request, 'hello/index.html', context)

9. データベースとモデル

Djangoではモデルを定義することで、データベース操作も簡単にできます。

1. モデルの定義

hello/models.pyに以下を追加:

from django.db import models

class Message(models.Model):
    text = models.CharField(max_length=100)

    def __str__(self):
        return self.text

2. マイグレーション

python manage.py makemigrations
python manage.py migrate

3. 管理画面に登録

hello/admin.pyに以下を追加:

from .models import Message
admin.site.register(Message)

これで管理画面からデータの追加・編集ができるようになります。


まとめ

  • Djangoは「コマンド1つ」で開発環境が作れる
  • ビュー・URL・テンプレート・モデルを組み合わせて簡単にWebアプリが作れる
  • 管理画面や認証など実践的な機能も標準搭載

まずはこの記事を参考に、自分だけのWebアプリを作ってみましょう!
慣れてきたら、フォームやユーザー認証、REST APIなどにもチャレンジしてみてください。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?