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:
        Channel('mychannel').send({
            '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.

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

Settings.py:

ALLOWED_HOSTS = ['175.228.35.250', 'myapp.com']

gunicorn.service:

[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/my_app
ExecStart=/home/ubuntu/my_app/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/my_app/my_app.sock my_app.wsgi:application
[Install]
WantedBy=multi-user.target

Nginx Code:

server {
  listen 80;
  server_name 175.228.35.250 my_app.com www.my_app.com;
  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'
        else:

            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'
        else:

            ###########################################
            #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 
exposures.tasks.process_exposure_file[27d7e651-e73e-49f1-bd20-8ab80b90d13a] 
raised unexpected: KeyError('BH_ENVIRONMENT_NAME',)
Traceback (most recent call last):
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/celery/app/trace.py", line 374, in trace_task
R = retval = fun(*args, **kwargs)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/celery/app/trace.py", line 629, in __protected_call__
return self.run(*args, **kwargs)
File "/home/bryan/PycharmProjects/BeachHouse/exposures/tasks.py", 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/manager.py", 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/query.py", line 397, in get
num = len(clone)
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", line 254, in __len__
self._fetch_all()
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", 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/query.py", line 50, in __iter__
db = queryset.db
File "/var/www/BeachHouse/bhvenv/lib/python3.6/site-
packages/django/db/models/query.py", 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/utils.py", line 258, in _route_db
chosen_db = method(model, **hints)
File "/home/bryan/PycharmProjects/BeachHouse/BeachHouse/db_routers.py", line 
16, in db_for_read
environment = os.environ['BH_ENVIRONMENT_NAME']
File "/var/www/BeachHouse/bhvenv/lib/python3.6/os.py", line 669, in 
__getitem__
raise KeyError(key) from None
KeyError: 'BH_ENVIRONMENT_NAME'

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

ENVIRONMENT_NAME = os.environ.get('BH_ENVIRONMENT_NAME')

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 celery.py 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.
app.autodiscover_tasks()

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:    http://agata.pgie.ufrgs.br/select_text
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/TextMining.py in separete_file_sentences, line 30
Python Executable:  /usr/bin/python3
Python Version: 3.4.3
Python Path:    
['/home/metis/public_html/AGATA',
 '/home/metis/public_html/AGATA/agataenv/lib/python3.4',
 '/home/metis/public_html/AGATA/agataenv/lib/python3.4/plat-x86_64-linux-gnu',
 '/home/metis/public_html/AGATA/agataenv/lib/python3.4/lib-dynload',
 '/usr/lib/python3.4',
 '/usr/lib/python3.4/plat-x86_64-linux-gnu',
 '/home/metis/public_html/AGATA/agataenv/lib/python3.4/site-packages']
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?

settings.py:

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'

STATICFILES_DIRS = (
    STATIC_PATH,
)

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 digitalocean.com. 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 godaddy.com. Domain settings are correct in accordance with the hosting tutorial https://www.digitalocean.com/community/tutorials/how-to-point-to-digitalocean-nameservers-from-common-domain-registrars:

ns1.digitalocean.com
ns2.digitalocean.com
ns3.digitalocean.com

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;
    server_name example.ru;

    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:
        #   http://en.wikipedia.org/wiki/X-Forwarded-For
        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;
            break;
        }
    }

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

Here are my settings for settings.py:

try:
    from .settings_prod import *
except:
    pass

Here are my settings for settings_prod.py:

    DEBUG = False
ALLOWED_HOSTS = ['0.80.00.000',
                 '.example.ru']

DATABASES = {
    '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 views.py 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 views.py 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 views.py 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
Exception:
Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/anaconda3/lib/python3.6/site-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/anaconda3/lib/python3.6/site-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 634, in _prepare_file
    abstract_dist.prep_for_dist()
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 129, in prep_for_dist
    self.req_to_install.run_egg_info()
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_install.py", line 412, in run_egg_info
    self.setup_py, self.name,
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_install.py", 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/__init__.py", 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/extension.py", 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/dist.py", 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>
    <h2>{{album.album_title}}</h2>
    <h3>{{album.artist}}</h3>
    <ul>
        {% for songs in album.song_set.all%}
            <li>{{songs.song_title}}- {{songs.file_type}}</li>
        {% endfor %}<br>
    </ul>
{% 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">
<head>
    <meta charset="UTF-8">
    <title>Isai</title>
    {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/>
    <link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="{% static 'music/Stylesheet.css' %}" type = "text/css"/>
</head>
<body>
  <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>
  </button>
  <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>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <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
        </a>
        <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>
        </div>
      </li>
    </ul>
  </div>
</nav>
{% block body %}
{% endblock %}
</body>
</html>

Installing Channels: Python Django version and settings

I’m trying to add Channels to my app by following this tutorial:
https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django

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

(virtualenv) root@computer:path# python manage.py runserver 0.0.0.0:8000

It gives error:

  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/routing.py", 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
https://github.com/VincentTide/django-channels-celery-example/issues/1
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 manage.py runserver 0.0.0.0:8000
Traceback (most recent call last):
  File "manage.py", 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:

channels==1.1.6
daphne==1.4.0
Django==1.9
eventlet==0.20.0

If I follow this tutorial: http://channels.readthedocs.io/en/1.x/getting-started.html

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 http://0.0.0.0:8000/
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/hub.py", line 457, in fire_timers
    timer()
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/hubs/timer.py", line 58, in __call__
    cb(*args, **kw)
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/semaphore.py", line 145, in _do_acquire
    waiter.switch()
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/eventlet/green/thread.py", line 41, in __thread_body
    func(*args, **kwargs)
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 99, in inner_run
    websocket_handshake_timeout=self.websocket_handshake_timeout,
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/daphne/server.py", line 101, in run
    websocket_handshake_timeout=self.websocket_handshake_timeout
TypeError: __init__() got an unexpected keyword argument 'proxy_forwarded_proto_header'

If I upgrade everything, except Python 2.7.12:

asgi-redis==1.4.3
asgiref==2.1.5
channels==2.0.2
daphne==2.0.3
Django==1.11.10

runserver will give:

  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/channels/apps.py", line 6, in <module>
    import daphne.server  # noqa
  File "/root/.virtualenvs/codebench/local/lib/python2.7/site-packages/daphne/server.py", 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

https://askubuntu.com/questions/966939/failed-building-wheel-for-twisted

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/tasks.py", line 241, in _step
    result = coro.throw(exc)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/channels/http.py", line 191, in __call__
    await self.handle(body)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/sync.py", line 108, in __call__
    return await asyncio.wait_for(future, timeout=None)
  File "/usr/lib/python3.5/asyncio/tasks.py", line 373, in wait_for
    return (yield from fut)
  File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
    future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/concurrent/futures/thread.py", line 55, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/sync.py", line 123, in thread_handler
    return self.func(*args, **kwargs)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/channels/http.py", line 227, in handle
    self.send(response_message)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/sync.py", line 62, in __call__
    return call_result.result()
  File "/usr/lib/python3.5/concurrent/futures/_base.py", line 405, in result
    return self.__get_result()
  File "/usr/lib/python3.5/concurrent/futures/_base.py", line 357, in __get_result
    raise self._exception
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/asgiref/sync.py", line 76, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/daphne/server.py", line 196, in handle_reply
    protocol.handle_reply(message)
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/daphne/http_protocol.py", line 210, in handle_reply
    http.Request.write(self, message.get("body", b""))
  File "/root/.virtualenvs/python3/lib/python3.5/site-packages/twisted/web/http.py", line 1084, in write
    self.channel.writeSequence(toChunk(data))
  'NoneType' object has no attribute 'writeSequence'

Also:

(python3) root@computer:path# python manage.py 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.
(InteractiveConsole)
>>> import channels
>>> print(channels.__file__)
/root/.virtualenvs/python3/lib/python3.5/site-packages/channels/__init__.py
>>> 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):
    try:
        if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1:
            print(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))
            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.