Djangoでアプリを作る~その2 下準備~

プログラミング

こんにちは

Djangoでアプリを作る~その1.ローカルサーバーを立てる~」の続きです。今回はアプリを具体的に組み立てていきたいと思います。

すなわち、HTMLやCSSをアプリの中に取り込んで、webサイト上で表示できるようにします。

スポンサーリンク

templatesとstaticディレクトリを作る

templatesとstaticというディレクトリを自分のアプリのディレクトリの中に作成します。

僕の場合は

translation(プロジェクト)
|-translateapp(アプリ)
    |-templates ←New!!
    |_static ←New!!

となります。

templatesディレクトリにアプリのhtmlを、staticディレクトリにアプリのcssを入れていきます。

しかし、そのままhtmlやcssを入れてしまうと同じアプリに同じ名前のテンプレートがあったときにDjangoが区別できないらしいです。

詳しくは公式ドキュメントをご覧ください

Django
The web framework for perfectionists with deadlines.

ですから、templates、staticディレクトリの下に、アプリと同じ名前のディレクトリを作成します。

⬇︎こんな感じ

translation(プロジェクト)
|_translateapp(アプリ)
    |-templates 
    |   |_translateapp ←New!!
    |_static 
        |_translateapp ←New!!

(めんどくさいですね…)

templatesディレクトリの中身

base.html

ではまず、使いまわせるhtmlを作ってしまいましょう。

templates/translationディレクトリのなかにbase.htmlを作り、以下のコードを入力してください。

{% load i18n static %}
<!DOCTYPE html>{% get_current_language as LANGUAGE_CODE %}
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% block extra_css %}
<link href="{% static 'translateapp/stylesheet.css' %}" rel="stylesheet">
{% endblock %}
<title>{% block title %}My books{% endblock %}</title>
</head>
<body>
  <div class="container">
    {% block content %}
      {{ content }}
    {% endblock %}
  </div>
{% block extra_js %}{% endblock %}
</body>
</html>

translate.html

次にbase.htmlの{{ content }}と{{ title }}部分を作成していきます。

base.htmlと同じ階層にtranslate.htmlをつくり、以下のコードを入力してください。

{% extends "translateapp/base.html" %}

{% block title %}翻訳機{% endblock title %}

{% block content %}
  <div class="title">
    <h1>翻訳機</h1>
  </div>

<div id="translate-area">

  <div id="en-input">
    <form id="ja-form" method="POST" >
      {% csrf_token %}
      <h3>英文</h3>
      <textarea class="form-control" id="input_text" name="input_text" rows="40" required>{{ input_text }}</textarea>
      <button id="translate-btn" type="submit" name="submit" value="送信" >
        翻訳
      </button>
    </form>
  </div>

  <div id="ja-output">
    <h3>日本文</h3>
    <textarea id="output_text" required>
      {{ text }}
    </textarea>
  </div>

</div>
{% endblock content %}

staticディレクトリの中身

stylesheet.css

stylesheet.cssはtranslate.htmlのデザインを決めています。

以下のコードをstatic/translationディレクトリのなかに作ってください。

body{
  font-family: "游ゴシック","HGP明朝B",sanserif;
}
.title h1{
  text-align: center;
}

#translate-area{
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -webkit-flex-direction: row;
  -ms-flex-direction: row;
  flex-direction: row;
  justify-content: center;
}
#ja-form{
  display: -webkit-flex;
  display: -ms-flex;
  display: flex;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  text-align: center;
  align-items: center;
  margin-right: 20px;
}

#input_text{
  width: 200px;
  height: 400px;
}

#translate-btn{
  background: #fff;
  border: 1px solid #000;
  color: #000;
  width: 100px;
  height: 50px;
  margin-top: 10px;
  transition: 0.4s all 0.3s ease;
}
#translate-btn:hover{
  background: #000;
  border: 1px solid #000;
  color: #fff;
}

#ja-output{
  text-align: center;
}

#output_text{
  width: 200px;
  height: 400px;
}

これでhtml,cssは終わりです!

view.pyを編集

次にhtmlの機能をつけていきます。

具体的には英文を日本文に翻訳したり、文字を出力したりする機能です。

では、次のコードをview.pyに書いてください。

from django.shortcuts import render

# Create your views here.
import re
from googletrans import Translator
from django.http import HttpResponse


def index(request):
    return render(request, 'index.html')

def translation(request):
    text = '翻訳します'
    try:
        input_text = request.POST['input_text']
        print(input_text)
        text = input_text
    except:
        return render(request,'translateapp/translation.html')

    comment_pattern = re.compile(r'//([^\n]*)')
    out = re.sub(comment_pattern, r'\1', text)

    out = re.sub(r'^\s*|\s*(?=\s)|\s*$', ' ', out)
    out = re.sub(r'[\r\n]', ' ', out)
    out = re.sub(r':\s+', r':\n', out)
    out = re.sub(r'\.\s+([A-Z])', r'.\n\1', out)

    out = ' '.join(
        '\n' + line if ' ' in line else line
        for line in out.splitlines())
    out = '\n'.join(
        re.sub(r' ([A-Z]\w+)', r' _\1_', line)
        for line in out.splitlines())
        
    text = ""
    for t in Translator().translate(out.strip().splitlines(), src='en', dest='ja'):
        text += t.text
        context = {
            'text': text,
        }

    return render(request,'translateapp/translation.html',context)

注意点としては

return render(request,'translateapp/translation.html',context)
などでhtmlのurlを指定するときにtemplatesからの相対urlに指定しなくてはいけないと言うことです。

例えば

'translateapp/translation.html'
をただ単に
'translation.html'
と指定してしまうとエラーします。

次にコードを簡単に解説すると、

まず、

def translation(request): 
       (中略)
        out = '\n'.join(
           re.sub(r' ([A-Z]\w+)', r' _\1_', line)
           for line in out.splitlines())
でテキストエリアに入力された文字列をoutに代入しています。

次にその文字列を改行してあるところで区切ってリストにし、(splitlines())その一つ一つの要素の文頭、文末の余白をなくします。(strip())

最後にそれぞれの要素を日本語に翻訳し、連結し直して出力します。

これでview.pyは完成です。

url.pyの変更

translation/url.pyの変更

次にプロジェクトディレクトリにあるurl.pyを変更します。

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

urlpatterns = [
    path('translateapp/', include('translateapp.urls')),
    path('admin/', admin.site.urls),
]

translateapp/url.pyの変更

では次にアプリのディレクトリにあるurl.pyを変更します。

from django.urls import path
from . import views

app_name = 'traslateapp'
urlpatterns = [
    path('translation/', views.translation, name='translation'),
    path('', views.index, name='index'),
]

もう一度ローカルサーバーを立てる

ではうまくいってるかサーバーを立てて確認してみましょう。

translationディレクトリにAnaconda promptで入り、開発環境を作って

python manage.py runserver 

と入力して、

http://localhost:8000/translateapp/translation

(translateapp/translationは templatesからの相対ディレクトリ)

とブラウザに入力して確認してみましょう!

こうなれば成功です!!

続きはこちら

参考

Djangoを最速でマスターする part1 - Qiita
初めに最近、「機械学習に強い」、「簡単」などの理由からPythonを選ぶ人が多いと思います。そんな人たちがWebを書こうと思った時にぶつかるのがDjangoの壁ですよね。(あれ、そんなことない…
Django
The web framework for perfectionists with deadlines.
Python Django入門 (4) - Qiita
Bootstrapの導入Django で CRUD を作る説明の前に、Bootstrapの導入を行います。我々エンジニアが作るHTMLは、デザイン的にも味気ないものとなってしまいます。そこで、…
タイトルとURLをコピーしました