Django Cookiecutter - django

I am trying to use Cookiecutter on a Digital Ocean server. (Not using Docker)
I followed the direction to install on Ubuntu 16 with Django, Postgres and Gunicorn. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
I can not get past the allowed host error.
DisallowedHost at /
Invalid HTTP_HOST header: '128.199.100.100:8000'.
You may need to add '128.199.100.100' to ALLOWED_HOSTS
I have the setting in production.py
ALLOWED_HOSTS = env.list ( 'DJANGO_ALLOWED_HOSTS',
default = [ '128.199.100.100' ] )
Do I need to change any setting to make it a production environment?
The only documentation on the Cookiecutter site is for pythonAnywere and Docker. http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-pythonanywhere.html
I just want a simple DO install. Can not find any documentation?
Thank you.

At this stage, you need to add '128.199.100.100:8000' (including the port) to your ALLOWED_HOSTS. You could set it as an environment variable in the runserver command:
ALLOWED_HOSTS = env.list ( 'DJANGO_ALLOWED_HOSTS',
default = [ '128.199.100.100', '128.199.100.100:8000' ] )
Or you could temporarily add it to the default in your settings.
DJANGO_ALLOWED_HOSTS=128.199.100.100:8000 ~/myproject/manage.py runserver 0.0.0.0:8000
Eventually, the tutorial will change gunicorn to use a socket file and you will access the website on port 80 with Nginx, so you won't need '128.199.100.100:8000' in your ALLOWED_HOSTS.

I had the similar problem and I believe I found a solution.
If you are using environmental variables that passes DJANGO_ALLOWED_HOST value (the most secure way of copying credentials when deploying).
Then look closely at the syntax where you are defining the list of IP addresses allowed for the host. The syntax of environmental variables is completely different from django environmental variables and that made me confused.
At first I defined DJANGO_ALLOWED_HOSTS using python syntax
export DJANGO_ALLOWED_HOSTS="['localhost', '127.0.0.1', '192.168.1.110']"
Which is completely incorrect as looking down the error message trace under Settings section, I got the following ALLOWED_HOSTS value
ALLOWED_HOSTS ["['localhost',", "' 127.0.0.1'"," ' 192.168.1.110']"
Which is just means the variables get parsed assuming completely different syntax. Making django settings into comma-separated string also didn't fix the issue
export DJANGO_ALLOWED_HOSTS="localhost, 127.0.0.1, 192.168.1.110"
The parsed result is the following, notice space character leading in the second and third element.
ALLOWED_HOSTS ['localhost', ' 127.0.0.1', ' 192.168.1.110']
It seems that the logic that parses address values is very particular and the only correct way of listing several hostsusing only comma as a separator.
export DJANGO_ALLOWED_HOSTS="localhost,127.0.0.1,192.168.1.110"

Related

Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS

I keep on getting this error whenever I run my server locally.
This is how allowed hosts is in my .env file ALLOWED_HOSTS=['*']
I have tried adding '127.0.0.1' to the .env file instead of * but nothing seems to be working.Any ideas?
Django doesn't read .env file by itself. You should care about it.
If you want Django reading environment variables, you should use os.environ.get() method at your settings.py. But environment variables must be available for django. Export it at command line or provide .env file to your docker container.
Also, you can use this library: https://django-environ.readthedocs.io/en/latest/

How to change 'localhost' url django

I want to play around with social-django authentication app. Iwant to add for login with facebook. For that I need to change my 127.0.0.1 to something like my-site.com. I wanted to change /etc/hosts, unfortunetely it doesn't exist.
I created hosts file using touch command and added 127.0.0.1 my-site.com (nothing more) and restarted my computer. I tried runserver command and copy-pasted hostname above to the beggining of the link (my-site.com:8000) but it didn't work.
My django project runs on venv.
If you have any ideas on solving my problem, please share
(I've posted a similar question on superuser.com, but no one seemed to know a solution there, so I ask here)
EDIT
my settings py now look like this
ALLOWED_HOSTS = ['my-site.com', '127.0.0.1']
But it still doesn't work
You can use localhost instead of 127.0.0.1 as one of the workaround.
Use this script:
$ python manage.py runserver localhost:8000
if you are on Mac or linux :
edit your /etc/hosts/ file and add
127.0.0.1 mysite.com
if you are on window:
Go to C:\Windows\System32\Drivers\etc\hosts and add
127.0.0.1 mysite.com
I am not sure about the mac and linux one but for windows it worked, hopefully it will work for others too.
You can use LocalTunnel ,it allows you to easily share a web service on your local development machine without messing with DNS and firewall settings.
Install Localtunnel globally (requires NodeJS) to make it accessible anywhere:
npm install -g localtunnel
Run django server using
python manage.py runserver
and use the command line interface to request a tunnel to your local server:
lt --port 8000
It will give you a temporary url to use in any place,You can use that url in other sysytems too,the url will be live until the server is running in your system.
You can also use the temporary url in facebook setting for testing purpose.
You need to change the file settings.py so that my-site.com is contained in the list of ALLOWED_HOSTS.
For security reasons Django needs to know what server names it servers, which is specified by ALLOWED_HOSTS. On Django's web site it states that:
A list of strings representing the host/domain names that this Django site can serve. This is a security measure to prevent HTTP Host header attacks, which are possible even under many seemingly-safe web server configurations.
Django Settings: ALLOWED_HOSTS
You need to buy, or get for free, a DNS (you can get a subdomain from Noip for free).
You then have to connect your domain to your router (search in the settings) and port forward your computer through the port you want. Now you will be able to visit "yourdomain.com" and you will get your django server.
Don't forget to add your domain to ALLOWED_HOSTS.
I wish it helps!
Before everything, you need to add your localhost domain to ALLOWED_HOSTS variable in settings.py:
ALLOWED_HOSTS = ['my-site.com', '127.0.0.1', 'localhost']
If you use PyCharm as your IDE, you can edit your configuration settings as so:
I posted a 7 step tutorial to achieve this with and without specifying the port, on a similar question for anyone still looking for a solution!

Django DJANGO_SETTINGS_MODULE changing back to 'config.settings.local' in Cookiecutter

I know my .env file is loading but for some reason it seems to be jumping back to 'config.settings.local'?
I am using the latest Cookiecutter code.
this is my .env settings.
DJANGO_ALLOWED_HOSTS=178.128.108.20,178.128.108.20:8000,*
DJANGO_ADMIN_URL=admin
DJANGO_DEBUG=True
DJANGO_SETTINGS_MODULE='config.settings.production'
DJANGO_SECRET_KEY=2l#$#-#2z...=6n7-ejd%+51
below are the settings I get back from Ubuntu after it can not find the allowed host setting.
The DJANGO_ALLOWED_HOSTS is set for the correct address but I get back an error about not being set.
Than I noticed some setting like the DJANGO_SETTINGS_MODULE have changed back to the local host.
Any ideas why?
Here is what I get back from my development server. Note the change in the config.setting to local.
And here is my disallowed host message back from Ubuntu.
As you can see the local host is set for this address.
here is the beginning Cookiecutter code:
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=True)
if READ_DOT_ENV_FILE:
# OS environment variables take precedence over variables from .env
env.read_env(str(ROOT_DIR.path('.env')))
All this admin stuff is not my thing. Sorry if it is foolish question.
Thanks.
I spent days chasing this issue and it turns out that if you do not set up Cookiecutter for either Heroku or Docker it does not set up the .envs folders that are needed.
Once I rebuilt the site with the Heroku option, I was able to solve my .envs issues.
use_heroku [n]: y
I can now set it up on Ubuntu (using Digital Ocean) and get the 'config.settings.production' to work.
Cheers.

502 Bad Gateway (nginx/1.10.3 (Ubuntu))

i sent my python3 django files to digital ocean server and getting 502 bad gateway error. I tried all the tips given elsewhere in stackoverflow but none worked. I believe there is something wrong with my settings.py. Specifically below lines, please let me know your suggestions:
ALLOWED_HOSTS = ['*']
# Find out what the IP addresses are at run time
# This is necessary because otherwise Gunicorn will reject the connections
def ip_addresses():
ip_list = []
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for x in (netifaces.AF_INET, netifaces.AF_INET6):
if x in addrs:
ip_list.append(addrs[x][0]['addr'])
return ip_list
# Discover our IP address
ALLOWED_HOSTS += ip_addresses()
Bad Gateway error sometimes comes even when there is an error in codes. It can be due to python version. Digital ocean uses 2.7, not 3.6. You have to upgrade Django to 1.11.
Make sure your directories inside \home\django_project\django_project are all well.
After all this in the ubuntu console by running python manage.py runserver like we used to do in local environment debug your errors. Don't look anywhere else, this is the best way and will work surely. I wasted 4 days in same error when I switched to production.
Good morning,
My solution in settings.py was:
ALLOWEDHOSTS = ['domainname', 'droplet_IP']
and add the bottom of settings.py
change:
ALLOWEDHOSTS = ipaddresses()
to
ALLOWEDHOSTS += ipaddresses()
Works in Feb '18.

Django can't find staticfiles with Debug=False and Allowed_Hosts

Hi all I'm having trouble solving this issue: If I turn DEBUG to False, I can't run manage.py runserver:
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False
Then, let's say I add something to ALLOWED_HOSTS:
ALLOWED_HOSTS = ['*']
or
ALLOWED_HOSTS = ['localhost']
or
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
Now, I can do ´manage.py runserver´ but the staticfiles don't work. Weird.
If I turn DEBUG to True, then it works with ALLOWED_HOSTS set to nothing, to localhost or to *. So, I guess the problem has to do with DEBUG. I don't understand it.
In DEBUG mode, the Django development server handles serving static files for you. However, this is not best for production as it's much more inefficient than a true server. See here.
Serving the files
In addition to these configuration steps, you’ll also need to actually serve the static files.
During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).
This method is grossly inefficient and probably insecure, so it is unsuitable for production.
See Deploying static files for proper strategies to serve static files in production environments.
Check out here to learn out how to serve static files in production.
EDIT: Adding the following to answer #alejoss question about viewing error pages with DEBUG=True.
I added something like the following to my root urls.py file:
if settings.DEBUG:
urlpatterns += patterns(
'',
url(r'^400/$', TemplateView.as_view(template_name='400.html')),
url(r'^403/$', TemplateView.as_view(template_name='403.html')),
url(r'^404/$', 'django.views.defaults.page_not_found'),
url(r'^500/$', 'django.views.defaults.server_error'),
)
You might need to alter a bit (i.e., the 400 and 403 pages may need to be edited if your template names are different). Basically, this lets you visit http://localhost/400 to see your 400 error page, http://localhost/403 to see your 403 error page, and so on.
If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:
manage.py runserver --insecure
Okay Here's the very clean solution. you need to use
DEBUG = False
DEBUG_PROPAGATE_EXCEPTIONS = True
This way in your logs you can see what is then problem. Whitenoise returns 500 usually when It is missing some file.
You can see what is missing in you logs. In my case heroku logs were enough.
for more info: https://docs.djangoproject.com/en/2.0/ref/settings/#debug-propagate-exceptions