Django (+Heroku)


[GitHub](https://github.com/takeshikondo/django_heroku)

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/f6a80dec-4d90-8753-c8c1-c6bab180e5ee.png)

![image.png](https://qiita-image-store.s3.amazonaws.com/0/254604/e4e762ec-f243-2c2d-adb3-7adaa30f5a06.png)


##Procfile
```python
web: gunicorn dj_project2.wsgi --log-file -
```

##runtime.txt
```python
python-3.6.6
```

##requirements.txt
```python
django
gunicorn
django-heroku
numpy
scikit-learn
gensim
Pillow
tensorflow
keras
```

##.gitignore
```python
db.sqlite3
.spyproject/*
```

##dj_project2/settings.py
```python
import os
import django_heroku

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

django_heroku.settings(locals())
```

##dj_project2/urls.py
```python
from django.contrib import admin
from django.urls import path, include

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

##dj_project2/wsgi.py
```python
import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_project2.settings')

application = get_wsgi_application()
```

##app1/urls.py
```python
from django.urls import path
from . import views

urlpatterns = [
        path('news_date/', views.app1_news_date, name='app1_news_date'),
        path('image/', views.app1_image, name='app1_image'),

]
```

##app1/forms.py
```python
from django import forms

class NewsDateForm(forms.Form):
    query_date = forms.DateField(
            label='Query Date',
            required=True,
            input_formats=[
                    '%Y-%m-%d',  # 2010-01-01
                    '%Y/%m/%d',  # 2010/01/01
                    ]
            )

class ImageForm(forms.Form):
    image = forms.ImageField()
```

##app1/views.py
```python
from django.http import HttpResponse
from django.shortcuts import render

from . import forms
from gensim.models.doc2vec import Doc2Vec
from PIL import Image
import numpy as np

from keras.models import load_model

def app1_news_date(request):
    model = Doc2Vec.load('./app1/models/doc2vec_model')
    
#    temp_doc = ['米ダウ平均', '上昇']
#    vector = model.infer_vector(temp_doc)

    if request.method == 'POST':
        form = forms.NewsDateForm(request.POST)
        
        if form.is_valid():
            q_date = form.cleaned_data['query_date']
           
            similar_dates = model.docvecs.most_similar(str(q_date), topn=3)
            
            d = {
                    'date1': similar_dates[0][0],
                    'date2': similar_dates[1][0],
                    'date3': similar_dates[2][0],
                    }
                       
            return render(request, 'app1/news_date_output.html', d)

    else:
        form = forms.NewsDateForm()
        
    d = {
            'form': form
    }
    
    return render(request, 'app1/news_date_input.html', d)

def app1_image(request):
    
    model = load_model('./app1/models/mnist.h5')        
    
    if request.method == 'POST':
        form = forms.ImageForm(request.POST, request.FILES)
        
        if form.is_valid():
            image = form.cleaned_data['image']
            x = np.reshape(np.array(Image.open(image)), (1,28,28,1))
            pred = np.argmax(model.predict(x)[0])
            
            d = {
                    'label': pred,
                    }
            
            #return HttpResponse(x)
            return render(request, 'app1/image_output.html', d)
        
        else:
            return HttpResponse('invalid form')
           
    else:
        form = forms.ImageForm()
        
    d = {
            'form': form
    }
    
    return render(request, 'app1/image_input.html', d)
```

##templates/app1/base.html
```html
<!DOCTYPE html>
<html>
<head lang="ja">
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
```

##templates/app1/news_date_input.html
```html
{% extends "app1/base.html" %}

{% block body %}
  <form method="post" action="">{% csrf_token %}
    {{ form.query_date.label }}：
    {{ form.query_date }}
    <br>
    <br>
    <input type="submit" value="送信" />
   </form>
{% endblock %}
```

##templates/app1/news_date_output.html
```html
{% extends "app1/base.html" %}

{% block body %}
  <div>
    Date 1: {{date1}} <br>
    Date 2: {{date2}} <br>
    Date 3: {{date3}} <br>
  </div>
  <br>
  <div>
    <a href="{% url 'app1:app1_news_date' %}">Back</a><br>
  </div>  
{% endblock %}
```

##templates/app1/image_input.html
```html
{% extends "app1/base.html" %}

{% block body %}
  <form method="post" action="" enctype="multipart/form-data">{% csrf_token %}
    {{ form }}
    <br>
    <br>
    <input type="submit" value="送信" />
   </form>
{% endblock %}
```

##templates/app1/image_output.html
```html
{% extends "app1/base.html" %}

{% block body %}
  <div>
    Label (prediction) :  {{label}}
  </div>
  <br>
  <div>
    <a href="{% url 'app1:app1_image' %}">Back</a><br>
  </div>  
{% endblock %}
```

##GitHub
```python
git add .
git commit -m "Initial Commit"

# 作成したGitHubリポジトリのURLをコピー&ペーストして、リモートブランチとして設定
git remote add origin https://github.com/your-name/project-name

# ローカルのファイルをアップロード
git push origin master

# if rejected
#git fetch
#git merge --allow-unrelated-histories origin/master
#git push origin master

# or
#git pull

# or
#git pull --allow-unrelated-histories origin/master

```