プログラミング

Django投票アプリ作成ガイド

Djangoを使用して投票アプリケーションを作成するための完全かつ包括的なガイドをお届けします。このガイドでは、Djangoフレームワークの基本から始め、投票機能を持つアプリケーションを作成するためのすべてのステップを詳細に説明します。Djangoを使った開発は、Webアプリケーションを迅速に構築できるため、初心者から上級者まで幅広く利用されています。それでは、さっそく投票アプリを作成するための手順を見ていきましょう。

1. 開発環境の準備

Djangoを使用する前に、PythonとDjangoがインストールされている必要があります。以下の手順で準備を進めましょう。

Pythonのインストール

DjangoはPythonで動作するため、まずはPythonをインストールします。公式サイト(https://www.python.org/downloads/)から最新バージョンをダウンロードし、インストールします。

Djangoのインストール

次に、Pythonのパッケージ管理ツールであるpipを使用してDjangoをインストールします。以下のコマンドをターミナルに入力します。

bash
pip install django

インストールが完了したら、Djangoのバージョンを確認してみましょう。

bash
django-admin --version

これで、Djangoのインストールが確認できました。

2. プロジェクトの作成

次に、新しいDjangoプロジェクトを作成します。以下のコマンドを使用して、プロジェクトを作成しましょう。

bash
django-admin startproject voting_project

このコマンドを実行すると、voting_projectというディレクトリが作成され、その中にDjangoプロジェクトの基本的な構成ファイルが作成されます。

bash
cd voting_project

次に、開発用のサーバーを起動して、プロジェクトが正常に作成されたか確認します。

bash
python manage.py runserver

ブラウザでhttp://127.0.0.1:8000にアクセスすると、Djangoの初期画面が表示されます。

3. アプリケーションの作成

投票機能を持つアプリケーションを作成します。以下のコマンドを使用して、新しいアプリケーションを作成します。

bash
python manage.py startapp polls

pollsというアプリケーションディレクトリが作成されます。このディレクトリ内に、アプリケーションのロジックやビュー、モデルなどを作成していきます。

4. モデルの作成

投票アプリケーションでは、投票の選択肢(Choices)と投票自体(Vote)を管理する必要があります。まず、polls/models.pyファイルに以下のコードを追加して、投票モデルを作成します。

python
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text

ここでは、QuestionモデルとChoiceモデルを作成しています。Questionモデルは投票の質問を保持し、Choiceモデルは各質問に対する選択肢を保持します。

5. モデルのマイグレーション

次に、作成したモデルをデータベースに反映させるためにマイグレーションを実行します。以下のコマンドを使用します。

bash
python manage.py makemigrations python manage.py migrate

これにより、データベースにQuestionおよびChoiceテーブルが作成されます。

6. 管理画面の設定

Djangoの管理画面を使って、投票の質問や選択肢を簡単に管理できるようにしましょう。polls/admin.pyファイルを編集して、以下のコードを追加します。

python
from django.contrib import admin from .models import Question, Choice admin.site.register(Question) admin.site.register(Choice)

これにより、管理画面からQuestionChoiceを管理できるようになります。

7. ビューの作成

次に、投票を表示するビューを作成します。polls/views.pyファイルを開いて、以下のコードを追加します。

python
from django.shortcuts import render, get_object_or_404 from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] return render(request, 'polls/index.html', {'latest_question_list': latest_question_list}) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question})

これで、index(最新の投票)、detail(質問の詳細)、results(投票結果)を表示するためのビューが作成されました。

8. URL設定

次に、アプリケーションのURLを設定します。polls/urls.pyファイルを作成し、以下の内容を追加します。

python
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('/', views.detail, name='detail'), path('/results/', views.results, name='results'), ]

これにより、各ビューに対応するURLパターンが作成されます。

9. テンプレートの作成

最後に、HTMLテンプレートを作成して、ビューで表示する内容を定義します。polls/templates/polls/ディレクトリを作成し、その中にindex.htmldetail.htmlresults.htmlを作成します。

index.html

html
html> <html> <head> <title>投票アプリtitle> head> <body> <h1>最新の質問h1> <ul> {% for question in latest_question_list %} <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}a>li> {% endfor %} ul> body> html>

detail.html

html
html> <html> <head> <title>{{ question.question_text }}title> head> <body> <h1>{{ question.question_text }}h1> <form action="{% url 'results' question.id %}" method="get"> {% for choice in question.choice_set.all %} <input type="radio" name="choice" value="{{ choice.id }}"> {{ choice.choice_text }}<br> {% endfor %} <input type="submit" value="投票"> form> body> html>

results.html

html
html> <html> <head> <title>{{ question.question_text }} の結果title> head> <body> <h1>{{ question.question_text }} の投票結果h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}: {{ choice.votes }}票li> {% endfor %} ul> body> html>

10. アプリケーションの実行

すべての設定が完了したら、再度開発用サーバーを起動して、ブラウザで投票アプリケーションを確認します。

bash
python manage.py runserver

ブラウザでhttp://127.0.0.1:8000にアクセスし、最新の投票を確認できるはずです。


これで、Djangoを使った投票アプリケーションの作成が完了しました。このアプリケーションは、ユーザーが投票し、その結果を表示する基本的な機能を備えています。さらに、管理画面を使用して投票内容を管理できるようになっており、実際のプロジェクトで使用するには十分な基盤が整っています。

Back to top button