Hosting an already made Django website with Heroku - python

I have already finished my website made with Django and would like to put it up. I found Heroku and saw that is free for my basic needs and would like to host it there. My site uses SQLite not PostgreSQL so I would like to know how to use that since it doesn't support sqlite. I found the getting started with Django page on Heroku but I didn't use pip or virtualenv to set it up.
What steps should I follow to get my site up? Just FYI I am using latest Django dev branch 1.8 and Python 3.4.1 and it is a personal website.
Here is my settings.py file
"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0r58%!j00w2q1faj*57=d)*fv^=ai#-wgnakj91^--z5f(ohq1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "templates"),
)
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)

You need a requirements.txt with all your dependencies, because heroku uses that file to provide you the services you need.
After you added the postgreSQL add-on to your heroku project, heroku generates you a DATABASE_URL environment variable. you can parse that in your settings.py according to heroku's tutorial:
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] = dj_database_url.config()
the basic wsgi.py is also provided in the tutorial, you can just use that.
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
commit the application to your local git repository and push it to the heroku remote repository. if you do that on the console you'll get good feedback about your deployment.
basically you need to follow the getting started tutorial. skipping the virtual environment stuff just makes generating the requirements file more complicated, but it is possible.

Related

ERROR: Template does not exist / Used: Django + React + heroku

I created a simple note with django & react app.
And I am trying to deploy to Heroku.
I tried heroku open at terminal, but this error page came out.
enter image description here
I don't have a folder named frontend.
Maybe it's a problem to try to find index.html from there.
Here is my environment and things i've tried.
File structure)
project-folder
api
env
build
index.html (Here)
public
src
package.json
mynote (my Django main app)
settings.py
manage.py
Procfile
requirements.txt
runtime.txt
requirements.txt)
asgiref==3.5.2
dj-database-url==0.5.0
Django==4.0.5
django-cors-headers==3.13.0
djangorestframework==3.13.1
gunicorn==20.1.0
psycopg2-binary==2.9.3
pytz==2022.1
sqlparse==0.4.2
tzdata==2022.1
whitenoise==6.2.0
runtime.txt)
python-3.10.0
Procfile)
release: python manage.py migrate
web: gunicorn djreact.wsgi --log-file -
settings.py)
"""
Django settings for mynotes project.
"""
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
# for heroku deploy
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '~')
# for heroku deploy
DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) )
ALLOWED_HOSTS = [
'[here is my project name!].herokuapp.com',
'127.0.0.1'
]
# Application definition
INSTALLED_APPS = [
~
'rest_framework',
'corsheaders',
'api',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
~
]
CORS_ALLOW_ALL_ORIGINS = True
ROOT_URLCONF = 'mynotes.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'build')
],
~
},
]
WSGI_APPLICATION = 'mynotes.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
AUTH_PASSWORD_VALIDATORS = [
~
]
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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
mynotes/urls.py)
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
re_path('^.*', TemplateView.as_view(template_name='index.html')),
]
output of termial after execute heroku open)
enter image description here
In 3000 port, 8000 port, my operation test worked as intended. (CRUD with RESTFUL api)
And i did the following in heroku, there was no error.
Except the heroku open
heroku login
heroku create [my server name]
git push heroku main
heroku run python manage.py migrate
And i installed buildpack.
heroku buildpacks:set heroku/python
heroku config:set DISABLE_COLLECTSTATIC=1
Thanks you

Why it shows Unknown command: 'collectstatic', when I try to collect-static

I am trying to deploy my Django project on Digital Ocean. I created my droplet and spaces on Digital Ocean and created a static folder to store my static files. I pulled my code from my github-repo. then I installed all requirements and tried to collect static files with command
python3 manage.py collectstatic
but it shows
Unknown command: 'collectstatic'
Type 'manage.py help' for usage.
what should I do here?
I checked my manage.py helper but it has no command as collectstatic
check,
compilemessages,
createcachetable,
dbshell,
diffsettings,
dumpdata,
flush,
inspectdb,
loaddata,
makemessages,
makemigrations,
migrate,
runserver,
sendtestemail,
shell,
showmigrations,
sqlflush,
sqlmigrate,
sqlsequencereset,
squashmigrations,
startapp,
startproject,
test,
testserver,
these are the commands in manage.py helper.
And my settings.py is the following
import os
from pathlib import Path
from decouple import config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = config('DEBUG', default=False, cast=bool)
SECRET_KEY = config("SECRET_KEY")
ALLOWED_HOSTS = ["134.209.153.105",]
ROOT_URLCONF = f'{config("PROJECT_NAME")}.urls'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'crispy_forms',
'accounts',
'adminn',
'student',
'union',
'chat',
'channels',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
]
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_ENDPOINT_URL = config('AWS_S3_ENDPOINT_URL')
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = config('AWS_LOCATION')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION)
TEMP = os.path.join(BASE_DIR, 'temp')
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
BASE_URL = "http://134.209.153.105"
here, in static url AWS_STORAGE_BUCKET_NAME, AWS_S3_ENDPOINT_UR, AWS_LOCATION are following...
AWS_STORAGE_BUCKET_NAME=studentcricle
AWS_S3_ENDPOINT_URL=https://sfo3.digitaloceanspaces.com
AWS_LOCATION=studentcircle-static
Thank you for those who checked my question.
My problem is solved as I run the following code.
export DJANGO_SETTINGS_MODULE=mysite.settings
I found it from Django documentation.
But I still did not find out what was the real problem.
It was something about my settings file. or multiple settings files
so, if anyone know the details, please describe it here. or in personal.
I think you should uncomment STATIC_ROOT inside your settings.py file and try this:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Try with replacing STATIC_ROOT in settings.py file with the following:
STATIC_ROOT = '/static/'
and whenever you run the python3 manage.py collectstatic command, make sure you are in the base directory where the manage.py file is located and there is a folder named static.
First of all please check if there is a folder in base directory named 'static'; if yes, then make a little change in the following code, remove'/' after static:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Secondly, make sure you have registered all the apps in the installed apps menu.
If the problem still persists, then try to run the following command: python manage.py shell
It should let you know where the problem is, if it's in the settings.

Django staticfiles of app does not copying in production after manage.py collectstatic

I'm using Django + Nginx + uwsgi
Settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main',
]
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
else:
STATIC_ROOT = "/var/www/mysite/static/"
STATIC_URL = '/static/'
if DEBUG:
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
else:
MEDIA_ROOT = "/var/www/mysite/media/"
MEDIA_URL = '/media/'
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
After update a code (in DEBUG = True all works good, static files are loading correct) I'm using python manage.py collectstatic on DEBUG = False in production server and it's collect admin static, but it's not collecting static for "main" app.
In debug mode all working good.
Checked serving by Nginx - it's working correct.
Why "collectstatic" doesn't collect static from "main" app?
UPD:
I'm an idiot. Forgot about add directory with static files in git. Sry.

Whitenoise + Django + Cloudfoundry - http 500 when compression is enabled

I've successfully deployed Django with Whitenoise on Cloudfoundry except for the compression. If I set on my settings.py to enable compression:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
I get a 500 error and nothing on my cf logs. Please not that I don't have SSH access nor/heroku as this is running on Predix.
My settings.py:
STATIC_URL = "/media/"
STATIC_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'itcave/media'),
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
wsgi.py:
from whitenoise.django import DjangoWhiteNoise
from django.core.wsgi import get_wsgi_application
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "itcave.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Please also note that all my static files are stored within a media folder at the same level as my settings.py file.
Adding web: python itcave/manage.py collectstatic --noinput on a line before my run command in Procfile didn't work. ALLOWED_HOSTS is correct because when DEBUG = True everything runs fine.

Can't login to Django admin using correct username and password

I have deployed a Django application on DigitalOcean using ngnix, gunicorn and a Postgresql database. Everything works just fine and when I run python manage.py syncdb and I'm able to create a user which populates my DB nicely.
Problem I'm having is that when I try to login to the Django admin interface I get prompted that I'm using the wrong username and/or password. I'm pretty sure the credentials are right as I have tried setting up the db multiple times.
Any ideas why Django thinks I'm inputing the wrong user info?
Thanks!
SETTINGS.py looks like
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXXXXXXXXXXXX'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
MIDDLEWARE_CLASSES = (
'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',
)
ROOT_URLCONF = 'qvido.urls'
WSGI_APPLICATION = 'qvido.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydbname',
'USER': 'user',
'PASSWORD': 'pass!',
'HOST': 'localhost',
'ROOT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/webapps/django-env/static/'
STATIC_URL = '/static/'
WSGI.py looks like
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qvido.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
EDIT
Ok, I aslo tried doing python manage.py dbshell and the select * from auth_user; I see the user I've created but still can't log in with it. So strange.
I apologize for the late answer, but I believe that this may be useful to someone.
I was having this same issue. After reading all of the comments to the original question, I was able to figure out what had happened.
During development, I had switched databases from an old test db to a new one which included all of the required tables rather than just changing the existing db. I had only changed the settings.py file to update the location of the new db, and did not touch the wsgi.py file. After migrating to the new db and removing the old file from the project, my admin user did not exist within the new database.
Based on comments by #Torsten Engelbrecht and the OP, all I needed to do was run the command suggested by #Alen thomas to make it functional again:
python manage.py createsuperuser
At this point I was able to set up the same admin account I'd used before, since it no longer existed. Now it all works fine. It might seem a little silly, but it pays to check the
So, I found the answer to why this was happening and indeed #scriptmonster was correct.
When I installed Django, Gunicorn etc. in my virtual-env I used sudo pip install which installed these outside of my virtaul-env.
I ran sudo chown -R myuser:myuser /webapps/myenv and then ran pip install django and pip install gunicorn again and everything worked just fine.

Categories

Resources