[PYTHON] Heroku deployment of the first Django app that beginners are addicted to

Due to various errands, I decided to deploy the locally made Django app to Heroku, but it took a long time, so as a memorandum.

environment

What is Django

(I think you know it when you read this article ...) Django seems to be a web framework that runs on Python2 and 3 ... It's "likely" because I'm not familiar with web frameworks. If you are interested, please refer to the official document ...?

Reference: Django documentation

What is deployment

Moving what was made in the local environment to the actual production environment ... Maybe. Web apps like Django weren't as easy as just uploading a website ... Below, I'll spell out the general flow of this deployment.

Prerequisites

If you haven't mastered Django yet, there was a nice article here, so learn from here ...! Explanation of Python Web application (Django) in an easy-to-understand manner even for beginners Master Django fastest

--General network environment (because you upload files) --Django app completed (using sqlite3 database) (virtualenv used) --CMD (command prompt) can be used --git installed --Heroku account owned

Deploy

The author who made the first web application using Django. It's slimy, it's moving, it's DB, it's moving One day, one day, it's finally time to move it online ... (story style)

Initial situation

DjangoApp/  ├ env/ (virtualenv)  ├ manage.py  ├ db.sqlite3 ├ Django App / (the one from the beginning)  │ ├ wsgi.py  │ └ setting.py └ App / (application body)

Eve of deployment

When I investigated what was necessary when deploying, "I put db.sqlite3 (sqlite database body), * .pyc, and env / and below in .gitignore". I made .gitignore obediently, deleted the cache with "git rm -r --cached." And committed

Reference: Reflect the settings of [Qiita] .gitignore

The situation after the night before

DjangoApp/  ├ env/  ├ manage.py  ├ db.sqlite3  ├ DjangoApp/  │ ├ wsgi.py  │ └ setting.py  ├ App/  └ .gitignore (New)

Ready to deploy

When uploading a file to Heroku, it seems that three kinds of sacred treasures "Procfile (without extension)" "requirements.txt" "runtime.txt" are required, so I will start creating

Procfile It tells Heroku that "This app should be launched like this! ☆" For the time being, I decided to write it exactly as it was written by various people.

Procfile


web: gunicorn DjangoApp.wsgi --log-file -

The Django App part describes your application name. And it seems that I have to install this "gunicorn" and so on in virtualenv later ... Mmm, it takes a lot of time and effort ...

requirements.txt You need to contact Heroku with the modules needed to run this application. Requirements.txt is used for that. (maybe) This is easy. After starting virtualenv with the command

CMD


pip freeze > requirements.txt 

And it is sufficient. You should have a file like the one below.

requirements.txt


Django==1.11.1
virtualenv==15.1.0

runtime.txt It seems to tell Heroku the version of python you are using now ... (I'm not sure)

CMD


python-2.7.x

The 2.7.x part is the version of Python installed on your computer.

After creating the three sacred treasures

DjangoApp/  ├ env/  ├ manage.py  ├ db.sqlite3  ├ DjangoApp/  │ ├ wsgi.py  │ └ setting.py  ├ App/  ├ requirements.txt (New)  ├ runtime.txt (New)  ├ Procfile (New)  └ .gitignore

Install Django-toolbelt

After investigating, it seems that various additional modules are required for deployment ... The above gunicorn, djando-static for handling static files, dj_database_url for handling databases, etc ... I think it is troublesome to handle each one. When I was there, I found an ally who could put these together! It's django-toolbelt ...!

CMD


pip install django-toolbelt

Install toolbelt as. All the necessary modules are available ...!

...... If you are a smart person, you should notice "this guy (laughs)" ... Yes, the module installed by toolbelt at this time is not written in requirements.txt ... I did not notice this for more than half a day Also spent time ... Correctly, let's update pip freeze again at this timing and update requirements.txt! !!

requirements.txt after installing toolbelt

requirements.txt


dj-database-url==0.4.2
dj-static==0.0.6
Django==1.11.1
django-toolbelt==0.0.1
gunicorn==19.7.1
psycopg2==2.7.3
pytz==2017.2
static3==0.7.0
virtualenv==15.1.0

It's still going on! Ready to deploy!

Next is the story around the database.

From what I hear, it seems that the sqlite3 database cannot be used on Heroku (I wonder if it can be installed ...?) Therefore, it is necessary to use (?) Postgres that is installed as standard on Heroku ...

…… And the dj-database-url for that! Open setting.py and find the following part.

setting.py


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

Rewrite the description about this DB as follows

setting.py


if "COMPUTER-NAME" in hostname:
    #Debug environment
    # DEBUG = True //I also switched the debug mode here
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    ALLOWED_HOSTS = [] #I'm not sure, but this seems to be important too
else:
    #Production environment
    # DEBUG = False
    import dj_database_url
    db_from_env = dj_database_url.config()
    DATABASES = {
        'default': dj_database_url.config()
    }
    ALLOWED_HOSTS = ['*']

This will use sqlite3 in your local environment and Postgres in your Heroku environment. (Likely) COMPUTER-NAME is the name of your device. (I saw that I should write local, but it didn't work in my environment ...) Also, if you (almost certainly) get angry with "I'm afraid you don't have a hostname!", Add the following to the beginning of setting.py.

setting.py


.
from socket import gethostname
hostname = gethostname()
.

I don't really understand wsgi

It's time to touch wsgi.py, which I haven't touched in the local environment ...! I think it's okay just to play with it a little like the following

setting.py


import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoApp.settings")
application = Cling(get_wsgi_application())

Django App has its own project name. …… After all, what was wsgi.py (Sorega Karanai)

Final situation

DjangoApp/  ├ env/  ├ manage.py  ├ db.sqlite3  ├ DjangoApp/  │ ├ wsgi.py (modified)  │ └ setting.py (modified)  ├ App/  ├ requirements.txt  ├ runtime.txt  ├ Procfile  └ .gitignore

Deploy now! Aim for Heroku!

Now that we're ready, launch CMD and head to Heroku!

CMD


git add .
git commit -am "Launching now!"

heroku login
> Enter your Heroku credentials.
> Email: [email protected]
> Password (hidden):
> Logged in as [email protected]

heroku create NAME
> https://NAME.herokuapp.com/ | https://git.heroku.com/NAME.git

git push heroku master
>Something long

heroku run python manage.py migrate
>The usual migrate command flows

heroku open

The final Heroku open will open the application for you. (In my case, it was the first Application Error ...) That's it! The rest is operation! !! Thank you for your hard work! !! !! (tired

Impressions

It's hard to write an impression about this, but it was so difficult for beginners to think, "What a detour ... Can't you make it smarter?" ... (´; ω; `) In particular, there are few references for the latest (ver1.11) ... After all, I was reading the official English document (laughs). Spread, Django's circle!

Unresolved bugs

Breaking management site

Deployed to Heroku safely ... I thought, but the management site ...

無題.png

It's broken ... (´ ・ ω ・ `) For some reason, it doesn't read CSS ... I added the following to setting.py to handle static files, but ... no ...!

setting.py


STATIC_URL = '/static/'

# Static asset configuration
STATIC_ROOT = 'staticfiles'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

...... Well, I will fix it patiently!

Recommended Posts

Heroku deployment of the first Django app that beginners are addicted to
The story that the version of python 3.7.7 was not adapted to Heroku
A story that is a little addicted to the authority of the directory specified by expdp (for beginners)
Freely customize the model. Change the variable name and field name of the model of the Django / Django Rest Framework app ~ How to reflect the deployment on heroku Memo
How to check the version of Django
Deploy the Django app on Heroku [Part 2]
Deploy the Django app on Heroku [Part 1]
10 Python errors that are common to beginners
The first web app created by Python beginners
Exclusive release of the django app using ngrok
List of links that machine learning beginners are learning
I want to upload a Django app to heroku
A magic word (?) That may save people who are addicted to building using the Intel compiler of Python + Numpy.
[Ansible] Example of playbook that adds a character string to the first line of the file
[Django] Let's try to clarify the part of Django that was somehow through in the test
When I deployed the Django app to Heroku, I got Module Not Found: <project-name> .wsgi.
python beginners tried to predict the number of criminals
The wall of changing the Django service from Python 2.7 to Python 3
Memo of deploying Django × Postgresql on Docker to Heroku
Miscellaneous notes about deploying the django app on Heroku
heroku deployment memo (Django)
Summary of stumbling blocks in Django for the first time
Hook to the first import of the module and print the module path
Try to extract the keywords that are popular in COTOHA
[Django] A collection of scripts that are convenient for development
[Django] A brief summary of the log output function so that even beginners can understand it.
The story of returning to the front line for the first time in 5 years and refactoring Python Django
[First personal development] The story of deploying the Flask app and Twitter's automatic reply bot on Heroku
The story that CSS is no longer applied after uploading the Django app from local to AWS
Deploy django project to heroku
The record I was addicted to when putting MeCab on Heroku
Extract the index of the original set list that corresponds to the list of subsets.
A story that struggled to handle the Python package of PocketSphinx
[Python] How to get the first and last days of the month
First python ② Try to write code while examining the features of python
The first artificial intelligence. How to check the version of Tensorflow installed.
How to deploy a Django app on heroku in just 5 minutes
Create an app that notifies LINE of the weather every morning
A script that returns 0, 1 attached to the first Python prime number
Verification of the theory that "Python and Swift are quite similar"
Python beginners hit the unofficial API of Google Play Music to play music
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A program that rotates the contents of the list to the left
The story of failing to update "calendar.day_abbr" on the admin screen of django
[For beginners] I want to get the index of an element that satisfies a certain conditional expression
(Python) I made an app from Trello that periodically notifies slack of tasks that are about to expire.
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
[AtCoder for beginners] A story about the amount of calculation that you want to know very roughly
Reasons to think that the Greek letters of formulas should be used as variable names as they are
Summary of sites and learning procedures that will be helpful for those who are trying to make games with pygame for the first time