Django to Heroku, How to migrate sqlite3 data to postgres - python

I tried to host a website on heroku but I keep getting this error
File
"/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py",
line 84, in _execute
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "home_product" does not
exist LINE 1: ...home_product"."price", "home_product"."slug" FROM
"home_prod...
whenever I tried to use
heroku run python
manage.py migrate -a appname
I mainly used this video as a reference to hosting.
and also this StackOverflow question and this article didn't shed much light on the issue.
Here's my settings.py
"""
Django settings for Corbett_Jewelry project.
Generated by 'django-admin startproject' using Django 3.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
import django_heroku
import dj_database_url
from decouple import config
import psycopg2
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
ALLOWED_HOSTS = ['127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home'
]
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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'Corbett_Jewelry.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'Corbett_Jewelry.wsgi.application'
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/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/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
django_heroku.settings(locals())
My models.py:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
image = models.ImageField(blank=True)
desc = models.TextField()
price = models.IntegerField()
slug = models.SlugField(unique=True, default=None)
def __str__(self):
return self.name
class Images(models.Model):
product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
img = models.ImageField(upload_to='images/')
def __str__(self):
return self.product.name
class Beads(models.Model):
name = models.CharField(max_length=200)
price = models.IntegerField()
img = models.ImageField(upload_to='beads/')
My Procfile:
web: gunicorn Corbett_Jewelry.wsgi
My requirements.txt:
asgiref==3.4.1
cycler==0.10.0
dj-database-url==0.5.0
Django==3.2.9
django-heroku==0.3.1
gunicorn==20.1.0
kiwisolver==1.3.2
matplotlib==3.4.3
numpy==1.21.2
Pillow==8.3.2
psycopg2==2.9.2
pyparsing==2.4.7
python-dateutil==2.8.2
python-decouple==3.5
pytz==2021.3
selenium==3.141.0
six==1.16.0
sqlparse==0.4.2
urllib3==1.26.7
whitenoise==5.3.0
I don't know what else information you might need to solve this. I'm happy to provide any info since I've been banging my head over this for a week now.

#Gamingapple... as you asked in the comments, I will attempt to provide all possible solutions I can think of for your issue.
I have never use Heroku, but here are the first solutions I would try:
1. A quick read from Heroku's help docs is showing you perhaps are not running migrations in the way that Heroku thinks are best practices for migrations: https://help.heroku.com/GDQ74SU2/django-migrations there (more-or-less) means you should be running your migrations locally, pushing up to Git, and then Heroku will automate the running of your migrations on deploy where it states:
Then, add the following as the first line in your Procfile:
release: python manage.py migrate
But note that this also means you should be using Postgres locally in development, not SQLite (as your title suggests).
-- Along with this, it appears you are trying to run migrations by app when you do: manage.py migrate -a appname, Django does have some regular migrations that need to be run so I'd just try manage.py migrate
2. You noted in the comment that dj_database_url.config() from PyPi's dj_database_url package: https://pypi.org/project/dj-database-url/ is returning an empty dictionary. To me, without extra info, I would say this is where your problem is when you manually try to run migrate in your Heroku instance; there is no database to find or connect to. To fix this I would remove the use of dj_database_url (as I have not used it either and we are debugging), and manually write my connection string for Django's DATABASES, like so:
pip install psycopg2 or just ensure it is in requirements/installed.
Change your DATABASES attr in settings to be manually written so you know what it is (we are debugging so perhaps after you get it up you make the password gathering more secure, like as an env variable)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '[HEROKU DB NAME]',
'USER': '[HEROKU DB USERNAME]',
'PASSWORD': '[HEROKU PASSWORD]',
'HOST': '{HEROKU HOST IP OR NAME FOR YOUR DB]',
'PORT': '[HEROKU DB PORT]',
}
}
Now with that correct, run the migration commands:
python manage.py makemigrations
python manage.py migrate

Related

python manage.py collectstatic not working: TypeError: sequence item 0: expected str instance, NoneType found

I have been following this video on Youtube: https://www.youtube.com/watch?v=inQyZ7zFMHM1
My project so far is working fine with static files and all the files load and work properly. So, now I have to deploy the website on Heroku and for that, I uploaded the database on Amazon AWS using this video.
After bucket creation, I did the configurations as mentioned in the video (copied the static files into the Bucket AWS) but it didn't work for me. It always showed me an error, that failed to load the resources
On searching, I found the command python manage.py collectstatic to upload files into Bucket so I tried it out but this is the error I keep on getting
TypeError: sequence item 0: expected str instance, NoneType found
I have searched a lot on this but unable to figure out what is the issue. This is also the same error which I got when I myself uploaded static files into Bucket and tried to upload a Profile Image
My settings.py file is as follows,
"""
Django settings for fcap project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
from django.contrib.messages import constants as messages
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-(c&774q+skzfb=n499li8!!!jv_m&s65eli3#w&zl+%c8h%sb$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fcap_users',
'rest_framework',
'storages',
]
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',
]
ROOT_URLCONF = 'fcap.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'fcap.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'fcap_db',
'USER': 'asad_hussain',
'PASSWORD': '(hidden for purpose)',
'HOST': 'database-2.cfhvhdusomqt.us-east-1.rds.amazonaws.com',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'fcap/static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = "/images/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# S3 Bucket Config
AWS_KEY_ACCESS_KEY_ID = '(hidden)'
AWS_SECRET_ACCESS_KEY = '(hidden)'
AWS_STORAGE_BUCKET_NAME = 'asad-hussain-fcap'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_S3_ADDRESSING_STYLE = "virtual"
This is my requirements.txt
asgiref==3.5.2
boto3==1.24.50
botocore==1.27.50
Django==4.1
django-filter==22.1
django-storages==1.13.1
djangorestframework==3.13.1
jmespath==1.0.1
Markdown==3.4.1
multielo==0.4.1
numpy==1.23.1
pandas==1.4.3
Pillow==9.2.0
psycopg2==2.9.3
python-dateutil==2.8.2
pytz==2022.1
s3transfer==0.6.0
six==1.16.0
sqlparse==0.4.2
tzdata==2022.1
urllib3==1.26.11
validate-email==1.3
My File Structure is as follows,
All the static files are working fine if they are on localhost but not working after the connection with AWS. However, the Postgres database is uploaded on AWS and it is working fine (that is, I can create users and etc using the AWS Database and they work fine.)
You have mispelled AWS_KEY_ACCESS_KEY_ID
It should be AWS_ACCESS_KEY_ID
The program expects a string against AWS_ACCESS_KEY_ID but because it is mispelled, so it is getting None instead. Due to this reason, you are getting an error that NoneType Found
Comment out the 'STATICFILES_DIRS' and try again. That was only used in my development.
also on a side note, i would remove the access keys from your bucket config when posting here. Even in production, they shouldn't be seen there. You can use a JSON config file or another method thats not accessable.

Django mange.py migrate --> No Migration folder and no tables created

I recently started to experiment with python and Django at the same time. After playing with several little projects from GitHub and or youtube and tried do it from scratch now on my own.
My problem is, the command
python manage.py migrate
Only creates those 10 "standard" Django and "auth" tables in my local mysql db.
Attached you can find my project structure. The way I started was with " django-admin startproject Nico".
Then step after step've created models, views, forms and templates.
My best guess is, the migrate command does not find the models file.
But I don't know where to specify that. At least that is a missing link. In my previous examples which were complete, I never had to declare that. Would that go in the right direction?
views.py
from django.views.generic.base import TemplateView
from ReProg.ReProg.models import Kunde
from ReProg.ReProg.forms import KundeForm
class HP(TemplateView):
Model = Kunde
Form = KundeForm
#template_name = "TestViewHello.html"
#template_name = "KundenAufnahme.html"
template_name = "KundenAufnahme2.html"
forms.py
from django import forms
from django.http import HttpResponse, HttpResponseNotFound
from django.shortcuts import render
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class KundeForm(forms.Form):
#KID = forms.CharField(attrs={'disabled': True})
KID = forms.CharField()
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'ReProg'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Wilhelm'}))
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '123#Mail.com'}))
def __init__(self, *args, **kwargs):
super(KundeForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.add_input(Submit('submit', 'Submit'))
Models.py
from django.db import models
from django.forms import ModelForm
from datetime import date
###########Kunde
class Kunde(models.Model):
KID = models.CharField(primary_key=True, max_length=20)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=100, blank=True)
def KID(key):
num = Request.objects.all().count()
return K + str(num)
class KundeMF(ModelForm):
class Meta:
model = Kunde
fields = ['first_name', 'last_name', 'KID']
settings.py
Django settings for ReProg project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+e69jgm56u85imt)(=6#82#c60222e9-z0+h8b+kxwhe(kc*z4'
# 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',
'ReProg',
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
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',
]
ROOT_URLCONF = 'ReProg.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'ReProg.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ReProg',
'USER': 'root',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/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/3.1/howto/static-files/
STATIC_URL = '/static/'
python manage.py makemigrations <app name>
python manage.py migrate <app name>
first make the following
python manage.py makemigrations
python manage.py migrate
if the problem did not solved make the following:
1- If the folder migrations did not found in the app directory create it.
2- If the folder found check the __init__.py file inside the folder.
if this file did not found create new file with name __init__.py.
it worked with adding the
i forgot to mention that before migrating I executed "makemigrations".
However it said "no changes detected" or something similar.
Now with the it works. I can see the table now in mysql.
[enter image description here][1]
thx all
[1]: https://i.stack.imgur.com/HaKFg.png

Python Django - Internal Error ProgrammingError relation does not exist

This might probably be a duplicated question, but I can't find a post to answer my questions yet. Any post that is similar to this may help is appreciated.
I tried to host my Django app using heroku.com
git add .
git commit -m "(commit_name)"
git push heroku master
When I tried to test the website (/questions/1), the website shows an Error 500 (Internal Error).
First it shows a ProgrammingError: relation does not exist.
After that I did $ heroku run python manage.py migrate try to solve the problem. The original error disappeared, but instead this happened:
2020-08-29T11:05:42.668070+00:00 app[web.1]: Internal Server Error: /questions/1
2020-08-29T11:05:42.668070+00:00 app[web.1]:
2020-08-29T11:05:42.668070+00:00 app[web.1]: DoesNotExist at /questions/1
2020-08-29T11:05:42.668071+00:00 app[web.1]: Question matching query does not exist.
Settings.py:
import django_heroku
from pathlib import Path
import os
#--------------------(ommited)--------------------#
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
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',
]
ROOT_URLCONF = 'myweb.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'myweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
LANGUAGE_CODE = 'zh-Hant'
TIME_ZONE = 'Asia/Taipei'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Activate Django-Heroku.
django_heroku.settings(locals())
Models.py:
from django.db import models
from django.utils import timezone
import json
# Create your models here.
class Code(models.Model):
code = models.TextField()
number = models.IntegerField()
class Question(models.Model):
title = models.TextField()
text = models.TextField()
judges = models.TextField()
number = models.IntegerField()
class Meta:
ordering = ['number']
def set_judges(self, x):
self.judges = json.dumps(x)
def get_judges(self):
return json.loads(self.judges)
wsgi.py:
import os
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myweb.settings')
application = Cling(get_wsgi_application())
Any suggestions or things I should try? Thank you.
[EDIT]: It seems that the database is empty now so it cause the error. But when I run the same file in my computer as I git push to heroku, the database isn't empty and it works fine.
According to your settings file, you are using sqlite as the database, and you can't use it in Heroku.
Heroku uses an an ephemeral filesystem.
You can write to it, and you can read from it, but the contents will
be cleared periodically. If you were to use SQLite on Heroku, you
would lose your entire database at least once every 24 hours.
That's why it works locally but not on Heroku, you need to use another database engine like postgresql for example.
Learn more about it at: https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

django docker db migrations is not working for the new model

I am new here in django docker.
I have created new model for django app, I am working on docker. When I am trying to use migrate command docker exec -ti 75ce87c91dc7 sh -c "python app/manage.py migrate", it says: No migrations to apply. Here I have added my models.py file, do we need to import this models to anywhere else?
Folder Structure :
settings.py
"""
Django settings for trialriskincApi project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xh86wu$_k#g46*+y9v_$2q^jnfg$uc44yh4+15nl2+2dx^$il%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'trialriskincApi',
]
MIDDLEWARE = [
'trialriskincApi.middleware.open_access_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',
]
ROOT_URLCONF = 'trialriskincApi.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 = 'trialriskincApi.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'trail_risk_inc_backend',
'USER': 'root',
'PASSWORD': '12345678',
'HOST': 'db', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/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/2.2/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/2.2/howto/static-files/
STATIC_URL = '/static/'
# Cors headers
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
models.py
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Userprofile(models.Model) :
user = models.OneToOneField(User, on_delete=models.CASCADE)
type = models.SmallIntegerField(max_length=1)
created_date = models.DateTimeField(default=timezone.now)
updated_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.updated_date = timezone.now()
self.save()
def __str__(self):
return self.title
If you are getting No changes detected that suggests that Django is not discovering your models.py, given that you are using the project as your app as well, I am guessing you forgot to add your project name (which is the same as your app name) in your INSTALLED_APPS.
e.g. in settings.py
INSTALLED_APPS = (
...
"trialriskincApi",
)
To migrate a new model you have to run
python manage.py makemigrations <yourAppName>
And for Docker you do like this:
docker exec -ti 75ce87c91dc7 sh -c "python app/manage.py makemigrations <yourAppName>

Django-admin page is missing select all checkbox on deploy

I've deployed my Django project on DigitalOcean.com. I've set static folder and run python manage.py collectstatic which worked correctly. The only problem is that I can't see select all checkbox in admin page.
This is in my local Django project:
And this is in deployed project:
I can't figure out where the problem is. Do you know?
I'm attaching settings.py of deployed project:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'some key'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main_app',
'django.contrib.admin',
'django_tables2',
'import_export',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'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 = 'drevo.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 = 'drevo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME':'/home/django/drevo/db.sqlite3',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/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',
},
]
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'email#gmail.com'
EMAIL_HOST_PASSWORD = 'pwd'
ADMIN_EMAIL = 'email#gmail.com'
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
VARS_MODULE_PATH = 'main_app.global_variables.py'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = '/home/django/drevo/static/'
STATIC_URL = '/static/'
I had the same problem and fixed it backing up all data in my static folder, emptying it and executing again:
python manage.py collectstatic
I figured out it was because of static files from a previous app I had installed (django-grappelli). Django was trying to move file needed to the destination /static/ folder, but as there were already the same files created by django-grapelli it just ignored them and doesn't moved them. Example:
Found another file with the destination path 'admin/css/dashboard.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
Emptying the folder I forced the command to recopy everything bak there and everything worked fine afterwards.
I just faced the same issue (at least same effects). It turned out to be (I think) a cache issue, either on nginx or on the client browser:
My production server works with Debian jessie, nginx, gunicorn, Django 1.10.2 + SSL.
To test if you have a cache problem, run (if your prod server allows this)
./manage.py runserver 0.0.0.0:8000
(or any other port you can access) on your production server for a short while. And test there if the checkbox is present. If yes, than just restart your server services and force the browser cache refresh a few times (hit shift+click on the refresh arrow on most of the browser I know).

Categories

Resources