- Pythonプログラム練習問題10問:Djangoを活用した実践的演習
- 1. Djangoとは?
- 2. 練習問題の概要と準備
- 3. 練習問題1: Hello Worldアプリケーションの作成
- 4. 練習問題2: テンプレートを使用した動的なコンテンツ表示
- 5. 練習問題3: URL設定によるルーティングの実装
- 6. 練習問題4: モデル定義とデータベース連携 (ORM)
- 7. 練習問題5: 管理サイトのカスタマイズ
- 8. 練習問題6: フォームの作成とデータの入力処理
- 9. 練習問題7: ユーザー認証機能の実装
- 10. 練習問題8: 静的ファイルの利用 (CSS, JavaScript)
- 11. 練習問題9: APIエンドポイントの作成
- 12. 練習問題10: テストコードの作成
Pythonプログラム練習問題10問:Djangoを活用した実践的演習
この記事では、PythonのWebフレームワークであるDjangoを使って、実践的なプログラミングスキルを向上させるための練習問題を10個紹介します。Djangoは、効率的なWebアプリケーション開発を可能にする強力なツールであり、これらの問題を通して、基本的な概念から応用まで幅広く理解することができます。
対象読者:
- Pythonの基礎知識がある方
- Webアプリケーション開発に興味がある方
- Djangoフレームワークを学びたい方
- プログラミングスキルを向上させたい方
前提条件:
- Python 3.xがインストールされていること
- Django 4.0以上のバージョンがインストールされていること (
pip install django
) - 仮想環境の利用を推奨します。 (
python -m venv myvenv; source myvenv/bin/activate
)
1. Djangoとは?
Djangoは、Pythonで書かれた高機能なオープンソースWebフレームワークです。Webアプリケーション開発を効率化するために設計されており、以下のような特徴があります。
- MTVアーキテクチャ: Model-Template-Viewと呼ばれるアーキテクチャを採用しており、コードの再利用性と保守性を高めます。
- Model: データベースの構造を定義し、データの操作を行います。
- Template: HTMLなどのテンプレートファイルで、Webページのデザインを記述します。
- View: ユーザーからのリクエストを受け取り、ModelやTemplateと連携してレスポンスを生成します。
- ORM (Object-Relational Mapper): Pythonのオブジェクトを使ってデータベースを操作できる仕組みを提供します。SQLを直接書く必要がなくなり、開発効率が向上します。
- セキュリティ: CSRF対策、XSS対策など、Webアプリケーションでよく発生するセキュリティリスクに対する保護機能を標準で備えています。
- 豊富な機能: ユーザー認証、フォーム処理、管理サイト、静的ファイル管理など、Webアプリケーションに必要な多くの機能を提供しています。
Djangoの公式サイト: https://www.djangoproject.com/
What is Django?
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It's known for its "batteries included" philosophy, meaning it comes with many built-in features to handle common web development tasks. Key aspects include:
- MTV Architecture: Stands for Model-Template-View. This architectural pattern separates concerns, making code more organized and reusable.
- Model: Represents data structures (e.g., database tables) and provides an interface for interacting with the database.
- Template: HTML files that define the presentation layer of your application. They can dynamically display data from models and views.
- View: Python functions that handle user requests, interact with models to retrieve or modify data, and render templates to generate responses.
- ORM (Object-Relational Mapper): Allows you to interact with databases using Python objects instead of writing raw SQL queries. This simplifies database operations and improves code readability.
- Security: Django provides built-in protection against common web vulnerabilities like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).
- Rich Features: Includes features for user authentication, form handling, an admin interface, static file management, and more.
2. 練習問題の概要と準備
以下の10個の問題を通して、Djangoの基本的な概念から応用までを実践的に学ぶことができます。各問題には、簡単な説明、実装手順、ヒントが含まれています。
対象読者:
- Pythonの基礎知識がある方
- Webアプリケーション開発に興味がある方
- Djangoフレームワークを学びたい方
- プログラミングスキルを向上させたい方
前提条件:
- Python 3.xがインストールされていること
- Django 4.0以上のバージョンがインストールされていること (
pip install django
) - 仮想環境の利用を推奨します。 (
python -m venv myvenv; source myvenv/bin/activate
)
準備:
- プロジェクトディレクトリを作成します:
mkdir django_practice; cd django_practice
- Djangoプロジェクトを作成します:
django-admin startproject practice .
(ドット(.)はカレントディレクトリに作成することを意味します) - アプリケーションを作成します:
python manage.py startapp myapp
注意: 各問題の実行後、必ず python manage.py runserver
コマンドでサーバーを起動し、ブラウザで動作確認を行ってください。
Overview of Practice Problems and Preparation
This article presents 10 practice problems designed to help you learn Django through hands-on experience. Each problem includes a brief explanation, implementation steps, and hints.
Target Audience:
- Individuals with basic Python knowledge
- Those interested in web application development
- People who want to learn the Django framework
- Anyone looking to improve their programming skills
Prerequisites:
- Python 3.x installed
- Django 4.0 or higher version installed (
pip install django
) - Using a virtual environment is recommended (
python -m venv myvenv; source myvenv/bin/activate
)
Preparation:
- Create a project directory:
mkdir django_practice; cd django_practice
- Create a Django project:
django-admin startproject practice .
(The dot (.) indicates creating the project in the current directory) - Create an application:
python manage.py startapp myapp
Note: After completing each problem, always run the server with the command python manage.py runserver
and verify its functionality in your browser.
3. 練習問題1: Hello Worldアプリケーションの作成
説明: Djangoプロジェクトを作成し、簡単なHello Worldを表示するビューとテンプレートを作成します。
実装手順:
myapp/views.py
ファイルに以下のコードを追加します。
from django.shortcuts import render def hello_world(request): return render(request, 'hello.html')
myapp/templates
ディレクトリを作成し、その中にhello.html
ファイルを作成します。
<!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, world!</h1> </body> </html>
practice/urls.py
ファイルに以下のコードを追加して、URLをビューにマッピングします。
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), # myappのURLを含める ]
myapp/urls.py
ファイルを作成し、以下のコードを追加します。
from django.urls import path from . import views urlpatterns = [ path('', views.hello_world, name='hello'), ]
- ブラウザで
http://127.0.0.1:8000/
にアクセスすると、"Hello, world!"と表示されるはずです。
Problem 1: Creating a Hello World Application
Description: Create a Django project and create a view and template to display a simple "Hello World."
Implementation Steps:
- Add the following code to
myapp/views.py
:
from django.shortcuts import render def hello_world(request): return render(request, 'hello.html')
- Create a directory named
myapp/templates
and create a file namedhello.html
inside it:
<!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, world!</h1> </body> </html>
- Add the following code to
practice/urls.py
to map the URL to the view:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), # Include myapp's URLs ]
- Create a file named
myapp/urls.py
and add the following code:
from django.urls import path from . import views urlpatterns = [ path('', views.hello_world, name='hello'), ]
- Access
http://127.0.0.1:8000/
in your browser; you should see "Hello, world!" displayed.
4. 練習問題2: テンプレートを使用した動的なコンテンツ表示
説明: テンプレートに変数やループ処理を組み込み、動的にコンテンツを表示します。
実装手順:
myapp/views.py
ファイルを以下のように修正します。
from django.shortcuts import render def hello_world(request): context = {'name': 'Django', 'items': ['apple', 'banana', 'cherry']} return render(request, 'hello.html', context)
myapp/templates/hello.html
ファイルを以下のように修正します。
<!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, {{ name }}!</h1> <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> </body> </html>
- ブラウザで
http://127.0.0.1:8000/
にアクセスすると、"Hello, Django!"とリストが表示されるはずです。
Problem 2: Displaying Dynamic Content Using Templates
Description: Incorporate variables and loop processing into templates to display dynamic content.
Implementation Steps:
- Modify
myapp/views.py
as follows:
from django.shortcuts import render def hello_world(request): context = {'name': 'Django', 'items': ['apple', 'banana', 'cherry']} return render(request, 'hello.html', context)
- Modify
myapp/templates/hello.html
as follows:
<!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, {{ name }}!</h1> <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> </body> </html>
- Access
http://127.0.0.1:8000/
in your browser; you should see "Hello, Django!" and a list displayed.
5. 練習問題3: URL設定によるルーティングの実装
説明: さまざまなURLパターンを定義し、それぞれのURLに対応するビューを設定します。
実装手順:
myapp/urls.py
ファイルに以下のコードを追加します。
from django.urls import path from . import views urlpatterns = [ path('', views.hello_world, name='hello'), path('about/', views.about, name='about'), # 新しいURLパターン ]
myapp/views.py
ファイルにabout
ビューを追加します。
from django.shortcuts import render def about(request): return render(request, 'about.html')
myapp/templates
ディレクトリを作成し、その中にabout.html
ファイルを作成します。
<!DOCTYPE html> <html> <head> <title>About</title> </head> <body> <h1>About Us</h1> <p>This is a simple about page.</p> </body> </html>
- ブラウザで
http://127.0.0.1:8000/about/
にアクセスすると、"About Us"と表示されるはずです。
Problem 3: Implementing Routing with URL Configuration
Description: Define various URL patterns and configure views to correspond to each URL.
Implementation Steps:
- Add the following code to
myapp/urls.py
:
from django.urls import path from . import views urlpatterns = [ path('', views.hello_world, name='hello'), path('about/', views.about, name='about'), # New URL pattern ]
- Add an
about
view tomyapp/views.py
:
from django.shortcuts import render def about(request): return render(request, 'about.html')
- Create a directory named
myapp/templates
and create a file namedabout.html
inside it:
<!DOCTYPE html> <html> <head> <title>About</title> </head> <body> <h1>About Us</h1> <p>This is a simple about page.</p> </body> </html>
- Access
http://127.0.0.1:8000/about/
in your browser; you should see "About Us" displayed.
6. 練習問題4: モデル定義とデータベース連携 (ORM)
説明: DjangoのORMを使ってモデルを定義し、データベースにデータを保存・取得します。
実装手順:
myapp/models.py
ファイルに以下のコードを追加します。
from django.db import models class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
- ターミナルで
python manage.py makemigrations myapp
コマンドを実行して、マイグレーションファイルを作成します。 - ターミナルで
python manage.py migrate
コマンドを実行して、データベースにテーブルを作成します。 myapp/views.py
ファイルに以下のコードを追加して、記事を一覧表示するビューを作成します。
from django.shortcuts import render, redirect from .models import Article def article_list(request): articles = Article.objects.all() return render(request, 'article_list.html', {'articles': articles}) def create_article(request): if request.method == 'POST': title = request.POST['title'] content = request.POST['content'] Article.objects.create(title=title, content=content) return redirect('article_list') # リダイレクト else: return render(request, 'create_article.html')
myapp/templates
ディレクトリを作成し、その中にarticle_list.html
とcreate_article.html
ファイルを作成します。practice/urls.py
ファイルに以下のコードを追加して、URLをビューにマッピングします。
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), # myappのURLを含める ]
myapp/urls.py
ファイルに以下のコードを追加します。
from django.urls import path from . import views urlpatterns = [ path('', views.article_list, name='hello'), path('articles/', views.create_article, name='create_article'), ]
Problem 4: Defining Models and Database Integration (ORM)
Description: Define models using Django's ORM and save/retrieve data from the database.
Implementation Steps:
- Add the following code to
myapp/models.py
:
from django.db import models class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
- Run the following command in the terminal:
python manage.py makemigrations myapp
to create a migration file. - Run the following command in the terminal:
python manage.py migrate
to create tables in the database. - Add the following code to
myapp/views.py
to create a view that lists articles:
from django.shortcuts import render, redirect from .models import Article def article_list(request): articles = Article.objects.all() return render(request, 'article_list.html', {'articles': articles}) def create_article(request): if request.method == 'POST': title = request.POST['title'] content = request.POST['content'] Article.objects.create(title=title, content=content) return redirect('article_list') # Redirect else: return render(request, 'create_article.html')
Create a directory named
myapp/templates
and create files namedarticle_list.html
andcreate_article.html
inside it.Add the following code to
practice/urls.py
to map URLs to views:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), # Include myapp's URLs ]
- Add the following code to
myapp/urls.py
:
from django.urls import path from . import views urlpatterns = [ path('', views.article_list, name='hello'), path('articles/', views.create_article, name='create_article'), ]
7. 練習問題5: 管理サイトのカスタマイズ
説明: Django管理サイトをカスタマイズして、モデルの表示方法や操作性を改善します。
(この問題は少し複雑になるため、ここでは概要のみ説明します。)
myapp/admin.py
ファイルを作成し、モデルを登録します:from .models import Article; admin.site.register(Article)
- 管理サイトの表示方法をカスタマイズするために、
list_display
,list_filter
,search_fields
などのメソッドを定義します。
Problem 5: Customizing the Admin Site
Description: Customize the Django admin site to improve the display and operability of models.
(This problem is a bit complex, so here's an overview.)
- Create a file named
myapp/admin.py
and register the model:from .models import Article; admin.site.register(Article)
- Define methods such as
list_display
,list_filter
, andsearch_fields
to customize the display of the admin site.
8. 練習問題6: フォームの作成とデータの入力処理
説明: Djangoのフォームを使って、ユーザーからの入力を検証し、データベースに保存します。
(上記の問題4のcreate_articleビューで既にフォームを使用しています。)
Problem 6: Creating Forms and Processing Input Data
Description: Use Django's forms to validate user input and save it to the database.
(This problem is already partially addressed in Problem 4 with the create_article
view.)
9. 練習問題7: ユーザー認証機能の実装
説明: Djangoの認証システムを使って、ユーザー登録、ログイン、ログアウト機能を実装します。
settings.py
ファイルでAUTH_USER_MODEL
を設定します。- URL設定に
login
,logout
,register
などのURLを追加し、対応するビューを定義します。 - テンプレートを作成して、フォームを表示し、認証処理を行います。
Problem 7: Implementing User Authentication Functionality
Description: Implement user registration, login, and logout functionality using Django's authentication system.
- Set
AUTH_USER_MODEL
in thesettings.py
file. - Add URLs for
login
,logout
, andregister
to the URL configuration and define corresponding views. - Create templates to display forms and perform authentication processing.
10. 練習問題8: 静的ファイルの利用 (CSS, JavaScript)
説明: CSSやJavaScriptを使って、Webページのスタイルやインタラクティブ性を向上させます。
settings.py
ファイルでSTATIC_URL
とSTATICFILES_DIRS
を設定します。- 静的ファイル (CSS, JavaScript, 画像など) をプロジェクトの適切なディレクトリに配置します。
- テンプレートで
<link>
や<script>
タグを使って、静的ファイルを読み込みます。
Problem 8: Using Static Files (CSS, JavaScript)
Description: Use CSS and JavaScript to improve the style and interactivity of web pages.
- Set
STATIC_URL
andSTATICFILES_DIRS
in thesettings.py
file. - Place static files (CSS, JavaScript, images, etc.) in an appropriate directory within your project.
- Use
<link>
and<script>
tags in templates to load static files.
11. 練習問題9: APIエンドポイントの作成
説明: Django REST frameworkを使って、APIエンドポイントを作成し、JSON形式でデータを返却します。
(この問題はDjango REST frameworkのインストールが必要です。)
Problem 9: Creating API Endpoints
Description: Create API endpoints using Django REST framework and return data in JSON format.
(This problem requires installing Django REST framework.)
12. 練習問題10: テストコードの作成
説明: Djangoのテストフレームワークを使って、ビューやモデルの動作を検証するためのテストコードを作成します。
myapp/tests.py
ファイルを作成し、テストケースを定義します。python manage.py test myapp
コマンドを実行して、テストを実行します。
Problem 10: Creating Test Code
Description: Create test code to verify the behavior of views and models using Django's testing framework.
- Create a file named
myapp/tests.py
and define test cases. - Run the following command in the terminal:
python manage.py test myapp
to execute tests.
このブログ記事は、Djangoの学習を始めるための良い出発点となるでしょう。各練習問題を一つずつ取り組むことで、Djangoの基本的な概念と機能を理解し、Webアプリケーション開発のスキルを向上させることができます。頑張ってください! This blog post should be a good starting point for learning Django. By working through each practice problem one by one, you can understand the basic concepts and functions of Django and improve your web application development skills. Good luck!