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
Related
I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:-
lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it.
filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp')
cpp_code=open(filepath,"w")
cpp_code.write(user_problem_code)
cpp_code.close()
I have tried to modify path in every possible way but got unlucky in every try
I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application
my project directory structure:
online_judge_project/
account/
homesrc/
language/ /* directory containing files in which I want to write */
forcpp.cpp
media/
oj/
settings.py
problempg/ /* application containing views.py */
views.py
static/
staticfiles/
template/
manage.py
settings.py
"""
Django settings for oj project.
Generated by 'django-admin startproject' using Django 4.0.5.
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 importlib.resources import path
from pathlib import Path
import os
from .info import *
EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
EMAIL_PORT = EMAIL_PORT
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'template')
FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language'))
# 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 = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["localhost","<MY_IP_ADDRESS>"]
# Application definition
INSTALLED_APPS = [
'widget_tweaks',
'account.apps.AccountConfig',
'problempg.apps.ProblempgConfig',
'homescr.apps.HomescrConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
]
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 = 'oj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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 = 'oj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 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_ROOT= os.path.join(BASE_DIR,'staticfiles')
STATIC_URL = 'static/'
MEDIA_ROOT= os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
LOGOUT_REDIRECT_URL = "index"
STATICFILES_DIRS=[
os.path.join(BASE_DIR, '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'
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am deploying it on Ubantu EC2 server or it's due to Nginx?
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
I am currently making a project in Django that has two models: Cards and Articles. Both cards and articles have a manager that should allow me to quickly instantiate instances of the class. For cards I have the following:
class CardsManager(models.Manager):
def create_card(self, card_name, geography, player, typestatus, _weighted_strength = 0):
card = self.update_or_create(card_name=card_name, geography=geography, player=player, typestatus=typestatus)
return card
This manager works smoothly and I have no issue uploading cards. However, my article manager is a different story. This is my article manager.
class ArticleManager(models.Manager):
def create_article(self, title, body, cardvar, source, datetime, readthrough, author):
article_item = self.update_or_create(title=title, body=body, card=cardvar, source=source, entry_date_time=datetime, read_through=readthrough, cardvar__card_name=cardvar, author=author)
return article_item
When I try to upload an article however, say in the following fashion:
article_entry = Article.objects.create_article('title', 'empty body', 'test_card_var', 'The_Source', '2019-12-30 02:03:04', 0, 'author')
I get the following error in my Powrshell when I simply attempt 'python manage.py runserver': LookupError: No Installed app with label 'admin'.
When I attempt to run 'python manage.py makemigrations' I get another long error message whose last line is 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'
I think the issue may have to do with something related to either 1) entry_date_time being a datetime object and passing a string (though I honestly am not sure how I'd pass a datetime object, what do they even look like) or b) the fact that cardvar is a ForeignKey pointing at the Cards model, which may not be allowed in an upload?
I really had no issues with uploading Cards but Articles has given serious issues. If anyone could help me resolve this issue it would be greatly appreciated, I'm still relatively new with Django and coding in general.
EDIT:
My Settings.py looks as follows:
"""
Django settings for newspaper_project project.
Generated by 'django-admin startproject' using Django 2.2.
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
#import django_heroku
#import psycopg2
#import dj_database_url
#import dotenv
#import psycopg2
#import dj_database_url, psycopg2
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#DATABASE_URL = os.environ['DATABASE_URL']
#conn = psycopg2.connect(DATABASE_URL, sslmode='require')
# 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 = ***********************
# 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',
#3rd party
'crispy_forms', #new
#Local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
'articles.apps.ArticlesConfig', #new
]
TIME_ZONE = 'America/New_York' #new
USE_TZ = True #TESTING THIS OUT
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 = 'newspaper_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #new
'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 = 'newspaper_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 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/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
AUTH_USER_MODEL = 'users.CustomUser' #new
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' #new
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = '**************************************'
EMAIL_PORT = 587
EMAIL_USE_TILS = True
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>
I keep getting this error when i try to import my models.py file into views.py or any of the other python script in my App directory,
I have the SECRET_KEY in settings.py and also add app in the list of INSTALLED_APPS,
wsgi.py contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') # I replaced my project name
manage.py also contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
I have checked through other people's installations in StackOverflow posts. My code works but importing models just break it
I use this command to import my class
from app_name.models import subscribers
and subscribers is defined thus
class subscribers(models.Model):
name = models.CharField('Name', max_length=120)
email = models.CharField('Email', max_length=120)
access_token = models.TextField()
expires_in = models.DateTimeField('token expiry date')
I have already executed makemigrations and migrate commands but being a newbie I don't know where else to look. Please save a soul it's been 3 days
thanks.
below is my settings.py
"""
Django settings for ps project.
Generated by 'django-admin startproject' using Django 2.2.6.
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
from oauth_outlook.views import gettoken
# 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='l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#'
#SECRET_KEY = os.environ.get("SECRET_KEY", "l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'oauth_outlook',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
'lockdown.middleware.LockdownMiddleware',
]
ROOT_URLCONF = 'ps.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 = 'ps.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# 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/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOCKDOWN_PASSWORDS = ('letmein', 'beta')
LOCKDOWN_VIEW_EXCEPTIONS = [
gettoken,
]
It looks like the following import is causing the problem:
from oauth_outlook.views import gettoken
Importing views or models in the settings can cause circular imports and lead to the SECRET_KEY error message even when it is set. I don’t like the way django-lockout is encouraging you to import views for the LOCKDOWN_VIEW_EXCEPTIONS setting.
I suggest you set LOCKDOWN_URL_EXCEPTIONS instead, then the import isn’t required.
LOCKDOWN_URL_EXCEPTIONS = (
r'^gettoken$', # replace with gettoken view
)