I have django project.
In my development, when error happens like not import modules... etc.
It shows the error on the browser, but I don't want to show that in production.
Where can I switch off the debug mode???
The settings.py file has a DEBUG setting [Django-doc]. You will furthermore need to specify the ALLOWED_HOSTS setting [Django-doc]. You can set this to False:
# settings.py
# …
DEBUG = False
ALLOWED_HOSTS = ['www.mywebsite.com']
# …
Note that some tooling of Django is not done when you work in a production environment, like serving static files. You will need to configure nginx/apache/… for that. For more information, see the Deploying static files section in the documentation.
here you should enter False or True in way your need. if my answer is correct pls check it for answered
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'this is security key'
# Turn off When Project Will published for use!
DEBUG = True
ALLOWED_HOSTS = [*] <-- this for plesk and Cpanel
# Application definition
INSTALLED_APPS = [ ' Your current app',' Your Seccond app ']
Related
I have a Django application where I'm handling environment variables using python-decouple and separate .env files. This works fine for variables that exist in both development and production environments, such as DEBUG.
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
While DEBUG has distinct values in each environment, other variables like SECURE_HSTS_SECONDS only need to be set in production and do not need to be set at all in development. I'm currently just hard-coding these values in my settings.py file:
if not DEBUG:
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_REFERRER_POLICY = 'same-origin'
SECURE_HSTS_PRELOAD = True
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
I suppose I could include these values in my dev .env file and just set them to their default values, but that seems unnecessary. Is there a cleaner way to implement this or a best practice? I'd prefer solutions that work with python-decouple
I didn't like the other answer because it seemed needlessly complex to add multiple settings files on top of already having separate .env files. I would have had to maintain separate env files, settings files, and wsgi.py/asgi.py files between my dev and prod environments.
Instead, I just included the same variables in my dev .env file as my prod .env file and manually set the default values. That way, I only need to maintain separate .env files between dev/prod. It would probably have been a little cleaner to just set the "default" parameter in the config() function within the settings file, but I liked the symmetry of each .env file having the same variables, so that was just a personal choice.
.env.dev :
DEBUG=True
ALLOWED_HOSTS=localhost, 127.0.0.1
SECURE_HSTS_SECONDS=0
SECURE_HSTS_INCLUDE_SUBDOMAINS=False
SECURE_HSTS_PRELOAD=False
SECURE_SSL_REDIRECT=False
SESSION_COOKIE_SECURE=False
.env.prod :
DEBUG=False
ALLOWED_HOSTS=mysite.com
SECURE_HSTS_SECONDS=2592000
SECURE_HSTS_INCLUDE_SUBDOMAINS=True
SECURE_HSTS_PRELOAD=True
SECURE_SSL_REDIRECT=True
SESSION_COOKIE_SECURE=True
settings.py :
DEBUG = config('DEBUG', cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
#HSTS settings
SECURE_HSTS_SECONDS = config('SECURE_HSTS_SECONDS', cast=int)
SECURE_HSTS_INCLUDE_SUBDOMAINS = config('SECURE_HSTS_INCLUDE_SUBDOMAINS', cast=bool)
SECURE_HSTS_PRELOAD = config('SECURE_HSTS_PRELOAD', cast=bool)
#HTTPS settings
SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT', cast=bool)
SESSION_COOKIE_SECURE = config('SESSION_COOKIE_SECURE', cast=bool)
It is best to have two (dev/prod) or three (base/dev/prod) settings files. This is done by setting the DJANGO_SETTINGS_MODULE env variable accordingly.
Therefore, you can put settings for you production environment into a different file. Also, you can go for the three files approach where you add common settings into a base.py file which you in turn import into the prod.py and dev.py files.
Find examples in the django docs.
I'm developing a django app locally and trying to configure it to use the Amazone SES service to send emails. I've installed django-ses and added this to my settings.py:
EMAIL_BACKEND = 'django_ses.SESBackend'
AWS_SES_REGION_NAME = 'us-west-2'
AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com'
AWS_ACCESS_KEY_ID = '...'
AWS_SECRET_ACCESS_KEY = '...'
Unfortunately, mail.get_connection() returns that it's still using django.core.mail.backends.console.EmailBackend; both in the shell and when the development server is running.
It behaved the same when I was attempting to go the normal smtp configuration route with django.core.mail.backends.smtp.EmailBackend too...
Any ideas as to why it's not making the switch?
According to the django docs the default value for EMAIL_BACKEND is django.core.mail.backends.smtp.EmailBackend, not django.core.mail.backends.console.EmailBackend, so it has probably been set again later in the settings file.
You can also print the value of EMAIL_BACKEND to make sure if the problem is in the function or the variable.
from django.conf import settings
print(settings.EMAIL_BACKEND)
Got a problem with Basic authentication in Django REST framework when debug mode is turned off. I am using Django 1.8.4 and Django REST Framework 3.2.2.
Looks like it saves credentials for all computers with the same IP address when the first is logged in. But after some time it prompts for the username and password again.
However, this problem does not occur when the debug mode in Django REST framework settings is set to True. I would like to have the same behaviour when debug is turned off. What is causing the problem?
In settings.py file add the host/domain-name of the system to which django is allowed to serve.
Use:
ALLOWED_HOSTS = ['127.0.0.1'] or ALLOWED_HOSTS = ['localhost'] so that django can serve the localhost.
You may also add other IP address as you wish.
Example:
ALLOWED_HOSTS = ['127.0.0.1', '192.1.12.23']
Domain names can also be accepted:
ALLOWED_HOSTS = ['www.example.com']
If you wish to serve many hosts, you may simply use *, as shown:
ALLOWED_HOSTS = ['*']
This will serve Django to any host in the world.
I'm having difficulty moving my django 1.9.3 app from local development to production on Heroku, specifically using allauth (0.25.2) to login via Twitter.
It appears I'm having the same problem as django allauth not working on production yet that answer does not work for me.
When I'm running the dev server, everything works with the callback url on twitter set to http://127.0.0.1:8000/accounts/twitter/login/callback/.
When I switch it to either http://{myappname}.herokuapp.com/accounts/twitter/login/callback/ or http://{myappname}.herokuapp.com/accounts/twitter/login/callback/ and access the app on Heroku, I get a 500 error when I try to login via Twitter, being redirected to https://{myappname}.herokuapp.com/accounts/twitter/login/?process=login
I'm including the following settings in settings.py, which I've tried toggling during my troubleshooting:
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_SUBJECT_PREFIX = "[{myappname}] "
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = {number}
ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = {number}
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
SOCIALACCOUNT_EMAIL_REQUIRED = ACCOUNT_EMAIL_REQUIRED
And for production (again, have tried toggling these):
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'
I've also tried refreshing the auth keys. Any ideas of what I'm doing wrong?
Taking e4c5's suggestion, I turned on debug in the production environment. This quickly lead to this question: Django: SocialApp matching query does not exist and the problem being with my SITE_ID configuration.
Late to the party here but you can try running a migration on Heroku.
heroku run python manage.py migrate
I'm using the same django codebase on multiple apps on heroku. My set up is using a git master branch and individual branches for each separate domain. However I'm struggling with the ideal solution of storing setting variables which are different for each app.
I was going down the route of storing them in environment variables, separate for each app on heroku. This would of been the ideal solution. However there are one or two admin functions which I currently only run locally in my app which needs to know the settings for each app. This means I'd have to store all the settings for each app in every apps environment. For instance:
instead of
site_email=blah#site.com
I'd end up with:
site1_email=blah#site1.com
site2_email=blah#site2.com
and so on...
I could do this but it just seems pretty messy to me. Are there any alternatives? I could rip out the offending functions and build them into their own app, but this seems alot of work just to hide app settings from each other.
given the following app setup:
/Project/
/app1/
/app2/
/project/ (the project app that gets auto created in Django 1.4+)
/settings/
__init__.py <- general site inspecific settings
sitea.py <- site A's specific settings
siteb.py <- site B's specific settings
inside sitea.py put Site specific settings (you can still use the os.environ.get() calls to use heroku stored settings).
# Default Django settings for project.
from project.settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
ALLOWED_HOSTS = []
MEDIA_ROOT = ''
STATIC_ROOT = ''
then in your heroku run/startup script do the equivalent of (I assume you'll be using gunicorn or some other production django server)
python manage.py runserver --settings=project.settings.sitea
Update - an example Project/project/settings/production.py file, note: all sensitive info reads from environment not from file.
from project.settings import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Francis', 'francis#teamcolab.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.environ.get('MYSQL_DATABASE'), # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': os.environ.get('MYSQL_USER'),
'PASSWORD': os.environ.get('MYSQL_PASSWORD'),
'HOST': os.environ.get('MYSQL_HOST'), # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': os.environ.get('MYSQL_PORT'), # Set to empty string for default.
}
}
REDIS = {
'HOST' : os.environ.get('REDIS_HOST'),
'PASSWORD' : os.environ.get('REDIS_PASSWORD', None),
'PORT' : int(os.environ.get('REDIS_PORT', 6379)),
'DB' : int(os.environ.get('REDIS_DB', 0)),
}
WEBSOCKET_URL = os.environ.get('WEBSOCKET_URL')
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['XX.com','production.XX.com','www.XX.com',]
SESSION_COOKIE_DOMAIN = '.XX.com'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.environ.get('MEDIA_ROOT')
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.environ.get('STATIC_ROOT')
Here's how we do it at The Motley Fool.
We have multiple settings files, one for each environment.
We have a defaults.py settings file which is the 'stock' for all environments.
We have settings files for each environment: testing.py, live.py etc.
These contain the changes from default (or completely different settings as needed).
We use Fabric + an internal deployer to deploy the right settings file to the right environment.
We have a fabfile that looks like this (simplified):
#task #def test():
"""sets environment to test"""
set_hosts(['testserver01.test.com', 'testserver02.test.com']) #servers to deploy to
env.environment = 'testing'
We have an internal deployer that scripts the creation of the environment:
def setup():
from fabric.api import cd, env
with cd(env.checkout):
env.run('python create_manage_script.py %s' % env.environment)
So when we deploy, here's what happens:
User runs fab {{environment}} deploy
Our deployer looks at the settings directory, and looks for a settings file that matches the environment name (testing/live/etc)
The deployer sends the appropriate commands to fabric,
Fabric deploys the code to that server and points the server to the correct settings file
It's important to note that we have three different environments (dev, test, live), and we have three different apps that use these three different environments.