LoginSignup
4
4

More than 3 years have passed since last update.

Djangoプロジェクトを作成して実行【2020新卒】

Last updated at Posted at 2020-06-30

この記事は2020年の新卒IT未経験の者が書きました。

少しでも分かりやすくこのPycharm公式ドキュメントの手順をかみ砕いた記事です。

プロジェクトの作成

まずは新規プロジェクトを作成します

5ef324f27571490048e59e79.png

プロジェクトタイプはDjangoを選択し、プロジェクト名(ProjctTest)とApplication name(Poppo)はお好きなものを・・・

5ef325927571490048e59e7a.png

CreateをクリックしこれでDjangoプロジェクトが準備完了。

プロジェクトの構造

作成したプロジェクトにはすでにフレームワーク固有のファイルとディレクトリが含まれています。

プロジェクトツールウィンドウのプロジェクトビューを見てみましょう。

5ef3274f7571490048e59e7c.png

これはDjango固有のプロジェクト構造を示しています。

PoPPo と ProjectTest ディレクトリ(さっき設定したお好きな名前で作成されている)
また、manage.py および settings.py ファイルが表示

今回中身を編集するファイルは
- ProjectTest/urls.py
- Poppo/models.py
- Poppo/views.py

になります。

Djangoサーバーの起動

では早速Djangoサーバーを起動してみましょう!

manage.py ユーティリティの runserver タスクを起動するだけです。

まずTerminalを開き

python manage.py runserver

と入力

5ef33645f67ca50048d05232.png

次にコンソールに表示されたURLをクリック

5ef33688f67ca50048d05233.png

この画面が表示されたら成功です🚀

5ef33692f67ca50048d05234.png

モデルの作成

次にmodels.pyを開いて、下記のコードを入力します。

このとき既にimport文があることに注意

from django.db import models

# the following lines added:
import datetime
from django.utils import timezone

class Question(models.Model):
   question_text = models.CharField(max_length=200)
   pub_date = models.DateTimeField('date published')

   def __str__(self):
       return self.question_text

   def was_published_recently(self):
       now = timezone.now()
       return now - datetime.timedelta(days=1) <= self.pub_date <= now

   was_published_recently.admin_order_field = 'pub_date'
   was_published_recently.boolean = True
   was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.DO_NOTHING,)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

データベースの作成

新しいモデル用のテーブルを作成する必要があります。

そこでmanage.pyコンソールをCtrl+Alt+Rで呼び出し、makemigrations Poppoを入力。

5ef33943f67ca50048d05237.png

Djangoに2つの新しいモデル、つまり Choice と Questionが作成されたことを伝え、migrationsフォルダを作成しました。

models.py

5ef33b61f67ca50048d0523c.png

作成されたmigrationフォルダ

5ef339e4f67ca50048d05239.png

5ef339faf67ca50048d0523a.png

次に再びmanage.pyコンソールで

sqlmigrate Poppo 0001

と入力。

5ef33d3ef67ca50048d0523d.png

最後にmigrate コマンドを実行して、データベースにこれらのテーブルを作成します。

5ef33d7df67ca50048d0523e.png

スーパーユーザーの作成

manage.py コンソールで createsuperuser コマンドを入力し、自分のメールアドレスとパスワードを指定します。

5ef33e3cf67ca50048d05240 (2).png

Superuser created successfully.と出たら作成完了。

実行/デバッグ構成の準備

これで管理者ページに移動する準備が整いました。

Djangoサーバーを実行し、ブラウザにアクセスし、アドレスバーにURL全体を入力することは可能ですが、PyCharmを使用すると簡単です。

あらかじめ設定されたDjangoサーバーの実行構成を少し変更して使用します。

ここを選択。

5ef3632cf67ca50048d0524b.png

Run/Debug Configurations ダイアログで、このRun/Debug Configurationsに名前(ここでは ProjectTest)を付け、デフォルトブラウザでアプリケーションの実行を有効にし(チェックボックスRun browserを選択)、デフォルトで開くサイトのページを指定します(ここでは http://127.0.0.1:8000/admin/です)。

5ef3654df67ca50048d0524c.png


これでOKをクリック

管理サイトの起動

アプリケーションを起動するには、Shift+F10を押すか、メインツールバーの Runボタン をクリックして、標準のDjangoサイトログインページを開きます。



5ef365e0f67ca50048d0524d.png
作成したスーパーユーザーでログイン。

5ef3671cf67ca50048d0524e.png

ログインすると、管理ページ(上の画像)が表示されます。認証と認可 (GroupsとUsers)セクションがありますが、投票(Questionの追加)は使用できません。なぜそうなるのでしょうか?

Question オブジェクトには管理インターフェースがあることを管理者に伝える必要があります。

そのために、Poppo/admin.py を開き、次のコードを入力します。

from django.contrib import admin
from .models import Question #this line added
admin.site.register(Question)#this line added

ページをリフレッシュし、質問の投票セクションが表示されていることを確認します。

追加完了。

5ef368baf67ca50048d05250.png

適当に質問を追加してみましょう。

5ef36946f67ca50048d05251.png

質問が追加されました。

5ef36964f67ca50048d05252.png

admin.pyの編集

質問に対しての選択肢はまだありません。

そこで再度 Poppo/admin.py を開き、次のように変更します。

from django.contrib import admin
from .models import Choice, Question

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

class QuestionAdmin(admin.ModelAdmin):
    fieldsets = [
            (None,               {'fields': ['question_text']}),
            ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
                ]
    inlines = [ChoiceInline]

admin.site.register(Question, QuestionAdmin)



ページをリフレッシュし、追加した質問をクリックし、選択肢の追加が表示されていることを確認。

選択肢や投票数を追加し保存する。

5ef36c27f67ca50048d05255.png

Viewの作成

ViewではIf文やWhile文、リスト、その他どのような構文もここで扱うことができるようになります。

そして関数化することで次のtemplateに渡すことができるのです。

さらにViewでは、関数ごとにどのHTMLファイルに情報を渡すのかを指定します。

それによりそれぞれの関数をtemplateに紐付けていくことになります。

Poppo/views.py を開き、次のコードを入力します。

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")


次に、urls.py という名前の新しいファイルを Poppo ディレクトリに追加し

5ef36fbaf67ca50048d05259.png


次のコードを入力します。

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.index, name='index'),
]



最後に ProjectTest/urls.py (PyCharmがすでに作成している)を編集し、インデックスページのURLを末尾に追加します。

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
    url(r'^Poppo/', include('Poppo.urls')), #this line added
    url(r'^admin/', admin.site.urls),
]

127.0.0.1:8000/Poppo/ を開いてみると・・・

5ef370cef67ca50048d0525c.png

次により多くのViewを追加してみます。

再度、Poppo/views.pyに次のコードを追加します。

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

次の url() 呼び出しを追加する新しいViewを Poppo/urls.py モジュールに配線(末尾に追記)します。

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: /Poppo/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /Poppo/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /Poppo/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

ブラウザで対応するページを開くと、次のように表示されます。

5ef3781d619aaa0048043a45.png


5ef3784b619aaa0048043a47.png


5ef37868619aaa0048043a48.png

Djangoテンプレートの作成

以上の通り、これらのページのデザインはビューにハードコードされています。

読みやすくするために、対応するPythonコードを編集する必要があります。

次に、Pythonからの出力の視覚的表現を分離しましょう。

そうするために、templateを作成しましょう。

Poppo/views.py を開き、その内容を次のコードに置き換えます。

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Question, Choice


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'Poppo/index.html', context)


def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'Poppo/detail.html', {'question': question})


def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'Poppo/results.html', {'question': question})


def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'Poppo/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('Poppo:results', args=(question.id,)))

ここで作成していないindex.htmlページを参照していることに気付くと思います。

PyCharmはクイックフィックスという機能があります。

電球をクリックするか Alt+Enterを押すと、対応するテンプレートファイルがtemplatesフォルダーに作成されます(PyCharmはこのテンプレートが存在するはずのディレクトリ Poppo も作成します)。

5ef37a26619aaa0048043a49.png

5ef37a43619aaa0048043a4a.png

5ef37a65619aaa0048043a4b.png

5ef37a83619aaa0048043a4c.png

同様にしてdetail.htmlとresults.htmlも作成します。

今のところ index.html は空です。次のコードを追加します。

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'Poppo/style.css' %}" />
{% if latest_question_list %}
           <ul>
    {% for question in latest_question_list %}
           <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
       </ul>
{% else %}
           <p>No polls are available.</p>
{% endif %}

スタイルシートの作成

Viewファイル index.htmlに見られるように、スタイルシート(.cssファイル)の参照があり、そしてまだ作成していません。

次のように作成します。

  1. ディレクトリを作成します。これを行うには、プロジェクトビューで、Pythonパッケージ Poppo を選択し、Alt+Insertを押します。

    5ef37d85619aaa0048043a4f.png

  2. 表示されるポップアップメニューでディレクトリを選択し、ディレクトリ構造 static/Poppoを指定します。

    5ef37df1619aaa0048043a50.png

  3. 次に、このディレクトリにスタイルシートを作成します。これを行うには、最も内側のディレクトリ Poppo/static/Poppoを選択し、Alt+Insertを押し、Stylesheetを選択して、表示されるダイアログでstyleを入力します。

    5ef37e31619aaa0048043a51.png


    5ef37e98619aaa0048043a52.png

  4. 好みに応じて、作成されたスタイルシートに下記のコードを追加(例:質問のリストを緑色の文字で表示)。

    li a {
    color: green;
    }

実行結果の確認

Runボタンをクリックしブラウザの

http://127.0.0.1:8080/admin/
http://127.0.0.1:8080/Poppo/に変更し入力して確認してみましょう。

5ef3817c619aaa0048043a53.png

出来ました。

これを参考に自分のページを育ててみましょう🌱

4
4
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
4
4