How to run code a single time on django channels server startup?

Django 1.7+ has AppConfig.ready (docs), however it seems to be running multiple times with Django Channels. How can I ensure that the code runs exactly once, even with multiple workers? I’m searching for a solution that works both with the dev server and with daphne.

Here is something I want to achieve:

from django.apps import AppConfig
from channels import Channel

class MyAppConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        # if thisIsTheFirstWorker:
            'text': 'message to be sent only once',

How to fix Django AWS EC2 Gunicorn ExecStart ExecStop end error?

I am trying to point my AWS Route 53 Domain to my EC2 IPv4 Public IP for my Django app, but I’m running into some gunicorn issues. The strange thing is that I am getting a successful nginx configuration messages, but yet it doesn’t work. I’ve already created a record set on Route 53.

gunicorn.service: Service lacks both ExecStart= and ExecStop= setting. Refusing.

ALLOWED_HOSTS = ['', '']


Description=gunicorn daemon
ExecStart=/home/ubuntu/my_app/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/my_app/my_app.sock my_app.wsgi:application

Nginx Code:

server {
  listen 80;
  location = /favicon.ico { access_log off; log_not_found off; }
  location /static/ {
      root /home/ubuntu/my_app;
  location / {
      include proxy_params;
      proxy_pass http://unix:/home/ubuntu/my_app/my_app.sock;

Nginx Test is successful but yet app won’t run:

ubuntu@ip-175-228-35-250:~$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Celery Worker not Inheriting Settings from Django App

I am developing a django app that has to process large spreadsheets that users upload – so naturally I turned to celery and rabbitmq. I successfully setup the environment and the task completes in the background successfully except for one issue: I use several environment variables (defined in my apache vhost file and passed to django by mod_wsgi) in a db router class to determine which database to use (i.e. production vs staging vs dev):

class DbRouter(object):

    def db_for_read(self, model, **hints):

        if model._meta.app_label == 'auth':
            return 'auth'
        elif model._meta.app_label == 'admin':
            return 'auth'
        elif model._meta.app_label == 'contenttypes':
            return 'auth'

            environment = environment = os.environ['BH_ENVIRONMENT_NAME']

            if environment == "staging":
                return 'staging'
            if environment == "production":
                return 'production'

    def db_for_write(self, model, **hints):

        if model._meta.app_label == 'auth':
            return 'auth'
        elif model._meta.app_label == 'admin':
            return 'auth'
        elif model._meta.app_label == 'contenttypes':
            return 'auth'

            #This is where django raises the exception#
            environment = os.environ['BH_ENVIRONMENT_NAME']

            if environment == "staging":
                return 'staging'
            if environment == "production":
                return 'production'

    def allow_migrate(self, db, app_label, model_name, **hints):
        return True

which works just fine in the regular django thread; however, when the background task attempts to use the db router I get the following key error (which seems to imply that os.environ dictionary is not available to the worker thread?):

[2018-02-16 14:23:01,516: ERROR/ForkPoolWorker-2] Task 
raised unexpected: KeyError('BH_ENVIRONMENT_NAME',)
Traceback (most recent call last):
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/celery/app/", line 374, in trace_task
R = retval = fun(*args, **kwargs)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/celery/app/", line 629, in __protected_call__
return*args, **kwargs)
File "/home/bryan/PycharmProjects/BeachHouse/exposures/", line 10, 
in process_exposure_file
exposure = Exposure.objects.get(pk=exposure_id)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/", line 397, in get
num = len(clone)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/", line 254, in __len__
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/", line 1179, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/", line 50, in __iter__
db = queryset.db
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/", line 1109, in db
return self._db or router.db_for_read(self.model, **self._hints)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/", line 258, in _route_db
chosen_db = method(model, **hints)
File "/home/bryan/PycharmProjects/BeachHouse/BeachHouse/", line 
16, in db_for_read
environment = os.environ['BH_ENVIRONMENT_NAME']
File "/var/www/BeachHouse/bhvenv/lib/python3.6/", line 669, in 
raise KeyError(key) from None

I attempted to fix this by adding the following to my file:


and updating the db router to use settings.ENVIRONMENT_NAME – however, when I print this out in the celery worker terminal it’s blank. My file is as follows (not sure if that’s relevant or not?):

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ['DJANGO_SETTINGS_MODULE'] = 'BeachHouse.settings'

app = Celery('BeachHouse')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('BeachHouse.settings', namespace='CELERY')

# Load task modules from all registered Django app configs.

so the question is: how do I pass the apache vhost variables to the celery workers – or alternatively, how do I get my django settings to this worker thread (that successfully load the apache variables)? I would like to stick with using the apache virtual host approach to define the variables if possible as there are many settings getting pulled from there.

FileNotFoundError Django on Apache (File Upload)

I’m trying to upload files in my development server, but can’t make it work. I
keep getting:

FileNotFoundError at /select_text
[Errno 2] No such file or directory: '/home/metis/public_html/AGATA\\media\\dados_petroleo.txt'
Request Method: POST
Request URL:
Django Version: 2.0.1
Exception Type: FileNotFoundError
Exception Value:    
[Errno 2] No such file or directory: '/home/metis/public_html/AGATA\\media\\dados_petroleo.txt'
Exception Location: /home/metis/public_html/AGATA/textMining/ in separete_file_sentences, line 30
Python Executable:  /usr/bin/python3
Python Version: 3.4.3
Python Path:    
Server time:    Fri, 16 Feb 2018 13:19:48 +0000

Perhaps it’s on /home/metis/public_html/AGATA\\media\\dados_petroleo.txt' , that should be /home/metis/public_html/AGATA/media/dados_petroleo.txt , but it’s using \\ …what’s going on?

STATIC_PATH = os.path.join(BASE_DIR,'static')

STATIC_URL = '/static/' # You may find this is already defined as such.

STATIC_ROOT = '/home/metis/public_html/static'


MEDIA_ROOT = '/home/metis/public_html/media'

MEDIA_URL = '/media/'

error Bad Request (400), when I go to the site on the domain

I started the django project on The problem is that on my ip address my site is loaded and there are no problems, but if I go through the domain, the “Bad Request error (400)”. Domain bought at Domain settings are correct in accordance with the hosting tutorial

Configuring nginx:

upstream bbb_app_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).

  server unix:/webapps/bbb/run/gunicorn.sock fail_timeout=0;

server {

    listen   80;

    client_max_body_size 4G;

    access_log /webapps/bbb/logs/nginx-access.log;
    error_log /webapps/bbb/logs/nginx-error.log;

    location /static/ {
        alias   /webapps/bbb/static/;

    location /media/ {
        alias   /webapps/bbb/media/;

    location / {
        # an HTTP header important enough to have its own Wikipedia entry:
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # enable this if and only if you use HTTPS, this helps Rack
        # set the proper protocol for doing redirects:
        # proxy_set_header X-Forwarded-Proto https;

        # pass the Host: header from the client right along so redirects
        # can be set properly within the Rack application
        proxy_set_header Host $http_host;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;

        # set "proxy_buffering off" *only* for Rainbows! when doing
        # Comet/long-poll stuff.  It's also safe to set if you're
        # using only serving fast clients with Unicorn + nginx.
        # Otherwise you _want_ nginx to buffer responses to slow
        # clients, really.
        # proxy_buffering off;

        # Try to serve static files from nginx, no point in making an
        # *application* server like Unicorn/Rainbows! serve static files.
        if (!-f $request_filename) {
            proxy_pass http://bbb_app_server;

    # Error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /webapps/bbb/static/;

Here are my settings for

    from .settings_prod import *

Here are my settings for

    DEBUG = False

    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db1',
        'USER': 'bbb',
        'PASSWORD': 'bbb',
        'HOST': 'localhost',
        'PORT': '',

checked nginx -t:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Creating a popup form in django

My django application has 4 buttons where each button opens a popup form upon clicking that button. After filling that popup form, my button should have right mark on it so that user can get to know that it is completed. Below these four buttons, i have submit button which posts all these forms details to database.

I can make a popup with modal in bootstrap. but i want this button to be clicked or set right mark on button after completing that popup form. I am confused on how to achieve this with django or bootstrap?

And also, do i have to create a separate view for every popup form in my django file? and how does that button store form values so that it will post these values upon clicking submit button?

Edit: my button looks like below

<button type="button" class="btn btn-default" data-toggle="modal" data-
target="#myModal">Button Name</button>

Upon clicking that above button, a popup appears which have form contains 4 fields. I want to get these form values in my file. But i do not have urlconf for that button. when i create a separate URL for the button, form no longer comes in popup or dialog box. How to get those form values in my file or how to process those form variables? Any help is appreciated

dIjango-websocket-redis Module Error on Installation

When I run django server, It says “ModuleNotFoundError: No module named ‘ws4redis'”.

When I try to install ws4redis using the PIP command, I says syntax error.

pip install django-websocket-redis

Here is the tracebacks of the errors:

Collecting django-websocket-redis
Using cached django-websocket-redis-0.5.1.tar.gz
Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/pip/", line 215, in main
    status =, args)
  File "/anaconda3/lib/python3.6/site-packages/pip/commands/", line 335, in run
  File "/anaconda3/lib/python3.6/site-packages/pip/", line 749, in build
  File "/anaconda3/lib/python3.6/site-packages/pip/req/", line 380, in prepare_files
  File "/anaconda3/lib/python3.6/site-packages/pip/req/", line 634, in _prepare_file
  File "/anaconda3/lib/python3.6/site-packages/pip/req/", line 129, in prep_for_dist
  File "/anaconda3/lib/python3.6/site-packages/pip/req/", line 412, in run_egg_info
  File "/anaconda3/lib/python3.6/site-packages/pip/req/", line 387, in setup_py
    import setuptools  # noqa
  File "/Users/ranjan/.local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg/setuptools/", line 2, in <module>
from setuptools.extension import Extension, Library
  File "/Users/ranjan/.local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg/setuptools/", line 5, in <module>
from setuptools.dist import _get_unpatched
  File "/Users/ranjan/.local/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg/setuptools/", line 103
    except ValueError, e:
SyntaxError: invalid syntax 

html file not extending

I extended the base file and the directory is correct and Iam still getting normal style.

{% extends "music/base.html" %} 
{% block body %}    
    {% load staticfiles %}
    <img src="{% static 'music/image/Robot-PNG-File.png' %}" class="rounded-circle" alt="face" style='max-height:200px'><br>
        {% for songs in album.song_set.all%}
            <li>{{songs.song_title}}- {{songs.file_type}}</li>
        {% endfor %}<br>
{% endblock %}

This is the base html.I copied this from bootstrap 4.0.I included the static files of bootstrap also.yesterday it worked fine.But today its not working

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
    <link href=',300,700' rel='stylesheet' type='text/css'
    <link rel="stylesheet" href="" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="{% static 'music/Stylesheet.css' %}" type = "text/css"/>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown link
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
{% block body %}
{% endblock %}

Installing Channels: Python Django version and settings

I’m trying to add Channels to my app by following this tutorial:

The Django app compiles, but when I try to run it:

(virtualenv) root@computer:path# python runserver

It gives error:

  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/", line 75, in resolve_routing
    raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e))
ImproperlyConfigured: Cannot import channel routing 'codebench.routing.channel_routing': cannot import name ProtocolTypeRouter

According to this
It maybe related to Python version, so I did:

(virtualenv) root@computer:path# alias python=python3
(virtualenv) root@computer:path# python -V
Python 3.5.2
(virtualenv) root@computer:path# python runserver
Traceback (most recent call last):
  File "", line 3, in <module>
    import eventlet
ImportError: No module named 'eventlet'
(virtualenv) root@computer:path# pip install eventlet
Requirement already satisfied: eventlet in /root/.virtualenvs/codebench/lib/python2.7/site-packages
Requirement already satisfied: greenlet>=0.3 in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from eventlet)
Requirement already satisfied: enum-compat in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from eventlet)
Requirement already satisfied: enum34 in /root/.virtualenvs/codebench/lib/python2.7/site-packages (from enum-compat->eventlet)

Now I stuck at: ImportError: No module named 'eventlet'

I have the following packages installed:


If I follow this tutorial:

System check identified 1 issue (0 silenced).
February 16, 2018 - 23:19:32
Django version 1.9, using settings 'codebench.settings'
Starting Channels development server at
Channel layer default (asgiref.inmemory.ChannelLayer)
Quit the server with CONTROL-C.
2018-02-16 23:19:32,935 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2018-02-16 23:19:32,935 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2018-02-16 23:19:32,935 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
2018-02-16 23:19:32,936 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive
Traceback (most recent call last):
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/hubs/", line 457, in fire_timers
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/hubs/", line 58, in __call__
    cb(*args, **kw)
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/", line 145, in _do_acquire
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/green/", line 41, in __thread_body
    func(*args, **kwargs)
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/django/utils/", line 226, in wrapper
    fn(*args, **kwargs)
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/management/commands/", line 99, in inner_run
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/daphne/", line 101, in run
TypeError: __init__() got an unexpected keyword argument 'proxy_forwarded_proto_header'

If I upgrade everything, except Python 2.7.12:


runserver will give:

  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/", line 6, in <module>
    import daphne.server  # noqa
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/daphne/", line 192
    async def handle_reply(self, protocol, message):
SyntaxError: invalid syntax

If I try to reinstall all required packages under Python 3.5.2:

Need this for twisted:

apt install python3.6-dev

Now I’m getting random errors:

2018-02-18 14:03:51,634 - ERROR - server - Exception inside application: 'NoneType' object has no attribute 'writeSequence'
  File "/usr/lib/python3.5/asyncio/", line 241, in _step
    result = coro.throw(exc)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/channels/", line 191, in __call__
    await self.handle(body)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/", line 108, in __call__
    return await asyncio.wait_for(future, timeout=None)
  File "/usr/lib/python3.5/asyncio/", line 373, in wait_for
    return (yield from fut)
  File "/usr/lib/python3.5/asyncio/", line 361, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.5/asyncio/", line 296, in _wakeup
  File "/usr/lib/python3.5/asyncio/", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/concurrent/futures/", line 55, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/", line 123, in thread_handler
    return self.func(*args, **kwargs)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/channels/", line 227, in handle
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/", line 62, in __call__
    return call_result.result()
  File "/usr/lib/python3.5/concurrent/futures/", line 405, in result
    return self.__get_result()
  File "/usr/lib/python3.5/concurrent/futures/", line 357, in __get_result
    raise self._exception
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/", line 76, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/daphne/", line 196, in handle_reply
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/daphne/", line 210, in handle_reply
    http.Request.write(self, message.get("body", b""))
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/twisted/web/", line 1084, in write
  'NoneType' object has no attribute 'writeSequence'


(python3) root@computer:path# python shell
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import channels
>>> print(channels.__file__)
>>> from channels import Group
Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: cannot import name 'Group'

Using django CSRF middleware with views returning JsonResponse

I want to use CSRF middleware with API Views in Django. Here is a demo view I want to use CSRF with, I am confused how to integrate CSRF here.

def login(request):
        if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1:
            return JsonResponse({'exit':'0','msg':'Success'})
        return JsonResponse({'exit':'2','msg':'User Invalid'})
    except Exception as e:
        return JsonResponse({'exit':'10','msg':'Unknown Error Occured'})

Any help or suggestions will be appreciated. Thanks.