difficulties to deploy a Django app on Heroku

Hey all,

I have several questions concerning this topic.
I created a simple blog app and want to deploy the app on Heroku. I deployed a Flask app with difficulties but this Django app is something!

I can run the app on localhost without issues. I am using the Heroku CLI to deploy the app.

  1. After commitment to GitHub I am trying:
(base) iMac-de-Mac:blog_application mac$ git push heroku master
Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 4 threads
Compressing objects: 100% (11/11), done.
Writing objects: 100% (11/11), 1.42 KiB | 1.42 MiB/s, done.
Total 11 (delta 8), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Building on the Heroku-20 stack
remote: -----> Using buildpack: heroku/python
remote: -----> Python app detected
remote: -----> Using Python version specified in runtime.txt
remote:  !     Python has released a security update! Please consider upgrading to python-3.9.13
remote:        Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Requirements file has been changed, clearing cached dependencies
remote: -----> Installing python-3.9.12
remote: -----> Installing pip 22.1.2, setuptools 60.10.0 and wheel 0.37.1
remote: -----> Installing SQLite3
remote: -----> Installing requirements with pip
remote:        Collecting asgiref==3.5.2
remote:          Downloading asgiref-3.5.2-py3-none-any.whl (22 kB)
remote:        Collecting dj-database-url==0.5.0
remote:          Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB)
remote:        Collecting Django==4.0.5
remote:          Downloading Django-4.0.5-py3-none-any.whl (8.0 MB)
remote:        Collecting django-heroku==0.0.0
remote:          Downloading django_heroku-0.0.0-py2.py3-none-any.whl (4.9 kB)
remote:        Collecting gunicorn==20.1.0
remote:          Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB)
remote:        Collecting sqlparse==0.4.2
remote:          Downloading sqlparse-0.4.2-py3-none-any.whl (42 kB)
remote:        Collecting whitenoise==6.2.0
remote:          Downloading whitenoise-6.2.0-py3-none-any.whl (19 kB)
remote:        Installing collected packages: dj-database-url, whitenoise, sqlparse, gunicorn, asgiref, Django, django-heroku
remote:        Successfully installed Django-4.0.5 asgiref-3.5.2 dj-database-url-0.5.0 django-heroku-0.0.0 gunicorn-20.1.0 sqlparse-0.4.2 whitenoise-6.2.0
remote: -----> $ python simple_blog/manage.py collectstatic --noinput
remote:        /tmp/build_0ad54a3c/simple_blog/staticfiles
remote:        Traceback (most recent call last):
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 24, in <module>
remote:            import psycopg2 as Database
remote:        ModuleNotFoundError: No module named 'psycopg2'
remote:        During handling of the above exception, another exception occurred:
remote:        Traceback (most recent call last):
remote:          File "/tmp/build_0ad54a3c/simple_blog/manage.py", line 22, in <module>
remote:            main()
remote:          File "/tmp/build_0ad54a3c/simple_blog/manage.py", line 18, in main
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute
remote:            django.setup()
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
remote:            apps.populate(settings.INSTALLED_APPS)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate
remote:            app_config.import_models()
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 304, in import_models
remote:            self.models_module = import_module(models_module_name)
remote:          File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
remote:            return _bootstrap._gcd_import(name[level:], package, level)
remote:          File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
remote:          File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
remote:          File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
remote:          File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
remote:          File "<frozen importlib._bootstrap_external>", line 850, in exec_module
remote:          File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module>
remote:            from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
remote:            class AbstractBaseUser(models.Model):
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 141, in __new__
remote:            new_class.add_to_class("_meta", Options(meta, app_label))
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 369, in add_to_class
remote:            value.contribute_to_class(cls, name)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/options.py", line 235, in contribute_to_class
remote:            self.db_table, connection.ops.max_name_length()
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/connection.py", line 15, in __getattr__
remote:            return getattr(self._connections[self._alias], item)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/connection.py", line 62, in __getitem__
remote:            conn = self.create_connection(alias)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 208, in create_connection
remote:            backend = load_backend(db["ENGINE"])
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 113, in load_backend
remote:            return import_module("%s.base" % backend_name)
remote:          File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
remote:            return _bootstrap._gcd_import(name[level:], package, level)
remote:          File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 28, in <module>
remote:            raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
remote:        django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'
remote: 
remote:  !     Error while running '$ python simple_blog/manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote: 
remote:        You may need to update application code to resolve this error.
remote:        Or, you can disable collectstatic for this application:
remote: 
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote: 
remote:        https://devcenter.heroku.com/articles/django-assets
remote:  !     Push rejected, failed to compile Python app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: !	Push rejected to app-of-simple-blog.
remote: 
To https://git.heroku.com/app-of-simple-blog.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/app-of-simple-blog.git'
(base) iMac-de-Mac:blog_application mac$

ok, it tells me: No module named 'psycopg2'
When I am installing psycopg2:

(base) iMac-de-Mac:blog_application mac$ pip install psycopg2
Collecting psycopg2
  Using cached psycopg2-2.9.3.tar.gz (380 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error
  
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [23 lines of output]
      running egg_info
      creating /private/var/folders/sj/rdh52j3j2w1f4pvw051w0dh00000gn/T/pip-pip-egg-info-ed7ypejm/psycopg2.egg-info
      writing /private/var/folders/sj/rdh52j3j2w1f4pvw051w0dh00000gn/T/pip-pip-egg-info-ed7ypejm/psycopg2.egg-info/PKG-INFO
      writing dependency_links to /private/var/folders/sj/rdh52j3j2w1f4pvw051w0dh00000gn/T/pip-pip-egg-info-ed7ypejm/psycopg2.egg-info/dependency_links.txt
      writing top-level names to /private/var/folders/sj/rdh52j3j2w1f4pvw051w0dh00000gn/T/pip-pip-egg-info-ed7ypejm/psycopg2.egg-info/top_level.txt
      writing manifest file '/private/var/folders/sj/rdh52j3j2w1f4pvw051w0dh00000gn/T/pip-pip-egg-info-ed7ypejm/psycopg2.egg-info/SOURCES.txt'
      
      Error: pg_config executable not found.
      
      pg_config is required to build psycopg2 from source.  Please add the directory
      containing pg_config to the $PATH or specify the full executable path with the
      option:
      
          python setup.py build_ext --pg-config /path/to/pg_config build ...
      
      or with the pg_config option in 'setup.cfg'.
      
      If you prefer to avoid building psycopg2 from source, please install the PyPI
      'psycopg2-binary' package instead.
      
      For further information please check the 'doc/src/install.rst' file (also at
      <https://www.psycopg.org/docs/install.html>).
      
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
(base) iMac-de-Mac:blog_application mac$

I am not sure what I should do with command:
python setup.py build_ext --pg-config /path/to/pg_config build ...
are the … meaning anything? Do I need to add just this code
(python setup.py build_ext --pg-config /path/to/pg_config build ...)
with the three points? And what should I do then? I am not familiar with this kind of syntax.

I installed pip install psycopg2-binary but the issue is the same and strangely terminal tells me:

(base) iMac-de-Mac:blog_application mac$ psycopg2-binary --version
-bash: psycopg2-binary: command not found
(base) iMac-de-Mac:blog_application mac$ pip install psycopg2-binary
Collecting psycopg2-binary
  Using cached psycopg2_binary-2.9.3-cp39-cp39-macosx_10_14_x86_64.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (2.2 MB)
Installing collected packages: psycopg2-binary
Successfully installed psycopg2-binary-2.9.3
(base) iMac-de-Mac:blog_application mac$ psycopg2-binary -v
-bash: psycopg2-binary: command not found
(base) iMac-de-Mac:blog_application mac$ 

I do not understand this?

  1. The requirements.txt file is also a bit of a problem I think.
    When I created the file with command:
    pip freeze > requirements.txt
    it was a mess with tons of dependencies and strange notes which I think I do not need. I have reduced the dependencies to the once which are written in the documentation of Heroku (a bit strange the documentation for me, really difficult for me) link: https://devcenter.heroku.com/articles/getting-started-with-python#install-app-dependencies-locally
    On this docs there is a list of dependencies needed for a Django app. I reduced the dependencies in requirements.txt to:
asgiref==3.5.2
dj-database-url==0.5.0
Django==4.0.5
django-heroku==0.0.0
gunicorn==20.1.0
sqlparse==0.4.2
whitenoise==6.2.0

in terminal I have this dependecies:

(base) iMac-de-Mac:blog_application mac$ pip list
Package                       Version
----------------------------- --------------------
aiohttp                       3.8.1
aiosignal                     1.2.0
alabaster                     0.7.12
anaconda-client               1.9.0
anaconda-navigator            2.2.0
anaconda-project              0.10.2
anyio                         3.5.0
appdirs                       1.4.4
applaunchservices             0.2.1
appnope                       0.1.2
appscript                     1.1.2
argon2-cffi                   21.3.0
argon2-cffi-bindings          21.2.0
arrow                         1.2.2
asgiref                       3.5.2
astroid                       2.6.6
astropy                       5.0.4
asttokens                     2.0.5
async-timeout                 4.0.1
atomicwrites                  1.4.0
attrs                         21.4.0
Automat                       20.2.0
autopep8                      1.6.0
Babel                         2.9.1
backcall                      0.2.0
backports.functools-lru-cache 1.6.4
backports.tempfile            1.0
backports.weakref             1.0.post1
bcrypt                        3.2.0
beautifulsoup4                4.11.1
binaryornot                   0.4.4
bitarray                      2.4.1
bkcharts                      0.2
black                         19.10b0
bleach                        4.1.0
bokeh                         2.4.2
boto3                         1.21.32
botocore                      1.24.32
Bottleneck                    1.3.4
brotlipy                      0.7.0
cachetools                    4.2.2
certifi                       2021.10.8
cffi                          1.15.0
chardet                       4.0.0
charset-normalizer            2.0.4
click                         8.0.4
cloudpickle                   2.0.0
clyent                        1.2.2
colorama                      0.4.4
colorcet                      2.0.6
conda                         4.13.0
conda-build                   3.21.8
conda-content-trust           0+unknown
conda-pack                    0.6.0
conda-package-handling        1.8.1
conda-repo-cli                1.0.4
conda-token                   0.3.0
conda-verify                  3.4.2
constantly                    15.1.0
cookiecutter                  1.7.3
cryptography                  3.4.8
cssselect                     1.1.0
cycler                        0.11.0
Cython                        0.29.28
cytoolz                       0.11.0
daal4py                       2021.5.0
dask                          2022.2.1
datashader                    0.13.0
datashape                     0.5.4
debugpy                       1.5.1
decorator                     5.1.1
defusedxml                    0.7.1
diff-match-patch              20200713
distributed                   2022.2.1
dj-database-url               0.5.0
Django                        4.0.5
django-heroku                 0.0.0
docutils                      0.17.1
entrypoints                   0.4
et-xmlfile                    1.1.0
executing                     0.8.3
fastjsonschema                2.15.1
filelock                      3.6.0
flake8                        3.9.2
Flask                         1.1.2
fonttools                     4.25.0
frozenlist                    1.2.0
fsspec                        2022.2.0
future                        0.18.2
gensim                        4.1.2
glob2                         0.7
gmpy2                         2.1.2
google-api-core               1.25.1
google-auth                   1.33.0
google-cloud-core             1.7.1
google-cloud-storage          1.31.0
google-crc32c                 1.1.2
google-resumable-media        1.3.1
googleapis-common-protos      1.53.0
greenlet                      1.1.1
grpcio                        1.42.0
gunicorn                      20.1.0
h5py                          3.6.0
HeapDict                      1.0.1
holoviews                     1.14.8
hvplot                        0.7.3
hyperlink                     21.0.0
idna                          3.3
imagecodecs                   2021.8.26
imageio                       2.9.0
imagesize                     1.3.0
importlib-metadata            4.11.3
incremental                   21.3.0
inflection                    0.5.1
iniconfig                     1.1.1
intake                        0.6.5
intervaltree                  3.1.0
ipykernel                     6.9.1
ipython                       8.2.0
ipython-genutils              0.2.0
ipywidgets                    7.6.5
isort                         5.9.3
itemadapter                   0.3.0
itemloaders                   1.0.4
itsdangerous                  2.0.1
jdcal                         1.4.1
jedi                          0.18.1
Jinja2                        2.11.3
jinja2-time                   0.2.0
jmespath                      0.10.0
joblib                        1.1.0
json5                         0.9.6
jsonschema                    4.4.0
jupyter                       1.0.0
jupyter-client                6.1.12
jupyter-console               6.4.0
jupyter-core                  4.9.2
jupyter-server                1.13.5
jupyterlab                    3.3.2
jupyterlab-pygments           0.1.2
jupyterlab-server             2.10.3
jupyterlab-widgets            1.0.0
keyring                       23.4.0
kiwisolver                    1.3.2
lazy-object-proxy             1.6.0
libarchive-c                  2.9
llvmlite                      0.38.0
locket                        0.2.1
lxml                          4.8.0
Markdown                      3.3.4
MarkupSafe                    2.0.1
matplotlib                    3.5.1
matplotlib-inline             0.1.2
mccabe                        0.6.1
mistune                       0.8.4
mkl-fft                       1.3.1
mkl-random                    1.2.2
mkl-service                   2.4.0
mock                          4.0.3
mpmath                        1.2.1
msgpack                       1.0.2
multidict                     5.2.0
multipledispatch              0.6.0
munkres                       1.1.4
mypy-extensions               0.4.3
navigator-updater             0.2.1
nbclassic                     0.3.5
nbclient                      0.5.13
nbconvert                     6.4.4
nbformat                      5.3.0
nest-asyncio                  1.5.5
networkx                      2.7.1
nltk                          3.7
nose                          1.3.7
notebook                      6.4.8
numba                         0.55.1
numexpr                       2.8.1
numpy                         1.21.5
numpydoc                      1.2
olefile                       0.46
openpyxl                      3.0.9
packaging                     21.3
pandas                        1.4.2
pandocfilters                 1.5.0
panel                         0.13.0
param                         1.12.0
parsel                        1.6.0
parso                         0.8.3
partd                         1.2.0
pathspec                      0.7.0
patsy                         0.5.2
pep8                          1.7.1
pexpect                       4.8.0
pickleshare                   0.7.5
Pillow                        9.0.1
pip                           22.1.2
pkginfo                       1.8.2
plotly                        5.6.0
pluggy                        1.0.0
poyo                          0.5.0
prometheus-client             0.13.1
prompt-toolkit                3.0.20
Protego                       0.1.16
protobuf                      3.19.1
psutil                        5.8.0
ptyprocess                    0.7.0
pure-eval                     0.2.2
py                            1.11.0
pyasn1                        0.4.8
pyasn1-modules                0.2.8
pycodestyle                   2.7.0
pycosat                       0.6.3
pycparser                     2.21
pyct                          0.4.6
pycurl                        7.44.1
PyDispatcher                  2.0.5
pydocstyle                    6.1.1
pyerfa                        2.0.0
pyflakes                      2.3.1
Pygments                      2.11.2
PyHamcrest                    2.0.2
PyJWT                         2.1.0
pylint                        2.9.6
pyls-spyder                   0.4.0
pyodbc                        4.0.32
pyOpenSSL                     21.0.0
pyparsing                     3.0.4
pyrsistent                    0.18.0
PySocks                       1.7.1
pytest                        7.1.1
python-dateutil               2.8.2
python-lsp-black              1.0.0
python-lsp-jsonrpc            1.0.0
python-lsp-server             1.2.4
python-slugify                5.0.2
python-snappy                 0.6.0
pytz                          2021.3
pyviz-comms                   2.0.2
PyWavelets                    1.3.0
PyYAML                        6.0
pyzmq                         22.3.0
QDarkStyle                    3.0.2
qstylizer                     0.1.10
QtAwesome                     1.0.3
qtconsole                     5.3.0
QtPy                          2.0.1
queuelib                      1.5.0
regex                         2022.3.15
requests                      2.27.1
requests-file                 1.5.1
rope                          0.22.0
rsa                           4.7.2
Rtree                         0.9.7
ruamel-yaml-conda             0.15.100
s3transfer                    0.5.0
scikit-image                  0.19.2
scikit-learn                  1.0.2
scikit-learn-intelex          2021.20220215.132722
scipy                         1.7.3
Scrapy                        2.6.1
seaborn                       0.11.2
Send2Trash                    1.8.0
service-identity              18.1.0
setuptools                    61.2.0
sip                           4.19.13
six                           1.16.0
smart-open                    5.1.0
sniffio                       1.2.0
snowballstemmer               2.2.0
sortedcollections             2.1.0
sortedcontainers              2.4.0
soupsieve                     2.3.1
Sphinx                        4.4.0
sphinxcontrib-applehelp       1.0.2
sphinxcontrib-devhelp         1.0.2
sphinxcontrib-htmlhelp        2.0.0
sphinxcontrib-jsmath          1.0.1
sphinxcontrib-qthelp          1.0.3
sphinxcontrib-serializinghtml 1.1.5
spyder                        5.1.5
spyder-kernels                2.1.3
SQLAlchemy                    1.4.32
sqlparse                      0.4.2
stack-data                    0.2.0
statsmodels                   0.13.2
sympy                         1.10.1
tables                        3.6.1
tabulate                      0.8.9
TBB                           0.2
tblib                         1.7.0
tenacity                      8.0.1
terminado                     0.13.1
testpath                      0.5.0
text-unidecode                1.3
textdistance                  4.2.1
threadpoolctl                 2.2.0
three-merge                   0.1.1
tifffile                      2021.7.2
tinycss                       0.4
tldextract                    3.2.0
toml                          0.10.2
tomli                         1.2.2
toolz                         0.11.2
tornado                       6.1
tqdm                          4.64.0
traitlets                     5.1.1
Twisted                       22.2.0
typed-ast                     1.4.3
typing_extensions             4.1.1
ujson                         5.1.0
Unidecode                     1.2.0
urllib3                       1.26.9
w3lib                         1.21.0
watchdog                      2.1.6
wcwidth                       0.2.5
webencodings                  0.5.1
websocket-client              0.58.0
Werkzeug                      2.0.3
wheel                         0.37.1
whitenoise                    6.2.0
widgetsnbextension            3.5.2
wrapt                         1.12.1
wurlitzer                     3.0.2
xarray                        0.20.1
xlrd                          2.0.1
XlsxWriter                    3.0.3
xlwings                       0.24.9
yapf                          0.31.0
yarl                          1.6.3
zict                          2.0.0
zipp                          3.7.0
zope.interface                5.4.0
(base) iMac-de-Mac:blog_application mac$

Is it wrong to delete nearly 90% of the dependencies?

But the current issue for the Heroku deployment is that I can not install psycopg2 . Can you guide me what are the next steps please? I am not sure about the info from terminal above.

  1. I installed Postgres. And set the $PATH as recommended in the docs of Postgres. But where or when should I use the command:
    export DATABASE_URL=postgres://$(whoami)
    which is displayed on this Heroku docs website: https://devcenter.heroku.com/articles/heroku-postgresql#local-setup at Local Setup?

  2. If you want to have a quick look to the settings.py. perhaps there is something wrong?

"""
Django settings for simple_blog project.

Generated by 'django-admin startproject' using Django 4.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path
import os
import django_heroku

# Build paths inside the project like this: BASE_DIR / 'subdir'.
# BASE_DIR = Path(__file__).resolve().parent.parent

# change BASE_DIR for Heroku deployment:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-0!(w*s7%d9)^l$%=d0yhixv)&$&0#j252q=+y8txk7ysfx91u2'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

    'blog_app',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # change for deployment on Heroku:
    # Simplified static file serving.
    # https://warehouse.python.org/project/whitenoise/
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'simple_blog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'simple_blog.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        # change NAME for the deployment on Heroku:
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
# STATIC_URL = 'static/'

# change for the deployment on Heroku:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = "/static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# Configure Django App for Heroku.
import django_heroku
django_heroku.settings(locals())


# deployment for Heroku:
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

the Procfile:

web: gunicorn simple_blog.wsgi
  1. For the Procfile I have an other question: on Heroku docs it is written:
    web: gunicorn myproject.wsgi
    What is myproject in my project tree?
    my tree looks like this:
  • blog_application
    • simple_blog
      • blog_app: templates, migrations, admin.py, …
      • simple_blog: settings.py, urls.py, …

Should ‘myproject’ be the first ‘simple_blog’ or the ‘simple_blog’ folder with settings.py file in it? And if it should be the ‘simple_blog’ with settings.py how do I set the Procfile right?

If you need further information please let me know. It would be great if you can help me understand this issue and solve it.

If you want to see more code the GitHub repo is: https://github.com/DoriDoro/simpleBlog

Thank you in advance
Doro

1 Like

Today was a new day and the installation of psycopg2 was no problem, strange! Whatever it was working.

The deployment is working now. I do not know if this is interesting for the community but I have done this steps:

requirments.txt:

Django==4.0.4
django-heroku
gunicorn
asgiref
psycopg2
whitenoise

With Django==4.0.5 the deployment was not working for me.

Procfile:
web: gunicorn --pythonpath simple_blog simple_blog.wsgi
OR
web: cd simple_blog && gunicorn simple_blog.wsgi

The settings.py file is in the second simple_blog folder that is why this path.

After deployment at Heroku with:
git push heroku master
I had to make migrations:
heroku run python simple_blog/manage.py migrate
the path is here important too.
and after the website was running and working.

Thanks for reading
Doro

1 Like