Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model and forms for questionnaire app
I'm stuck on creating my app that allows to create and fill surveys. This is my current model: class Question(models.Model): TYPES = ( ('SCH', 'Single choice'), ('SCO', 'Single choice with other'), ('MCH', 'Multiple choice'), ('MCO', 'Multiple choice with other'), ('TXT', 'Text'), ) survey = models.ForeignKey('Survey') text = models.CharField(max_length=1000, null=False) type = models.CharField(max_length=3, choices=TYPES) possibleAnswers = models.CharField(max_length=3000, null=False) # JSON class QuestionResponse(models.Model): surveyResponse = models.ForeignKey('SurveyResponse') question = models.ForeignKey('Question') answer = models.CharField(max_length=3000, null=False) # JSON I thought it's ok but now I don't know how to make forms for that. I want to let users create types of questions listed in TYPES. At the beginning, user chooses question type: Choice or Text (in the future possibly there will be more types). Then, if he selected Choice, he can add as many answers as he wants and decide if he wants other option and multiple choice option. With my model I can't create form as simple subclass of ModelForm. Various number of answers is also very hard to implement for me. Can you give me tips how to manage to implement that app? -
When I try to publish a post to a predefined date it doesn't work in my django app
When I try to publish a post to a later date It doesn't work. It simply publishes the post with the later date. for instance if I create a post on 4/9/2017 which is today but I select 4/28/2017 as the publish date, it will simply publish the post today with todays date on it. When I select a future date I want it published on that date. I'm not a django pro and until recently never had to post in the future just the day of. In addition to posting on a particular day in the future. I would also like to select the time the post is posted. Here is my code models.py from django.db import models from django.core.urlresolvers import reverse from taggit.managers import TaggableManager from django.db.models.signals import pre_save from django.utils.text import slugify from django.utils import timezone from django.contrib.auth.models import User class Greeting(models.Model): when = models.DateTimeField('date created', auto_now_add=True) class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') # relative to media_cdn i.e. media_cdn/20/car.jpg def upload_location(instance, filename): return "{}/{}".format(instance.id, filename) class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique_for_date='publish') image = models.ImageField(upload_to=upload_location, null=True, blank=True, height_field='height_field', width_field='width_field') image_url = models.CharField(max_length=500, null=True, blank=True, ) … -
Django + AngularJS + AJAX
Is it posible to build site like google analytics by using AngularJS on front-end, and Django on back-end. Menu is static, but when you click on link, content dynamicaly refresh by ajax, without any REST service. -
Django: Do I need not to think about 'select_related' or 'prefetch_related' if I used 'django-cachalot'?
I found that django-cachalot(http://django-cachalot.readthedocs.io/en/latest/index.html), which looks very good for caching for novice. If I used this library, Do I need not to use select_related or prefetch_related? For example, Can I use just class ClienListView(LoginRequiredMixin, AjaxListView): model = ClienPost context_object_name = "posts" template_name = "clien/clien_list.html" page_template = 'clien/clien_list_page.html' def get_queryset(self): posts = ClienPost.objects.all() return posts instead of class ClienListView(LoginRequiredMixin, AjaxListView): model = ClienPost context_object_name = "posts" template_name = "clien/clien_list.html" page_template = 'clien/clien_list_page.html' def get_queryset(self): posts = ClienPost.objects.select_related('category').prefetch_related('cliencomment_set').all() return posts ?? -
Django csrf token when posting multiple forms
I am trying to create a page that includes multiple forms, and I want to build something like a "like button" so that one can "like" some posts in a page. Now I encounter a problem that I can only "like" a post. When I click another "like" to another post, csrf error would occur(CSRF verification failed. Request aborted.). I want to know how to like multiple posts in a page at the same time. Does it have something to do with how and where to put {% csrf_token %}? This article(How Will the Inclusion of Two Forms Affect my CSRF Token Use?) says I should put {% csrf_token %} in every form, but it doesn't seem to work. Here's my code: models.py class Restaurant(models.Model): name = models.CharField(max_length=20) phone_number = models.CharField(max_length=15) address = models.CharField(max_length=50, blank=True) likes = models.DecimalField(max_digits=2,decimal_places=0, default=0) views.py <!doctype html> <html> <head> <title> Menu </title> <meta charset='utf-8'> </head> <body> <h2>餐廳列表</h2> <table> <tr> <th>ID</th> <th>NAME</th> <th>PHONE</th> <th>ADDRESS</th> <th>LIKES</th> <th>LIKE IT!</th> </tr> {% for r in restaurants %} <tr> <td> {{ r.id }} </td> <td> {{ r.name }} </td> <td> {{ r.phone_number }} </td> <td> {{ r.address }} </td> <td> {{ r.likes }} </td> <td> <form id={{ r.id }} action="" … -
Django Haystack + Solr attribute error
Following a tutorial and trying to use Django with Haystack and Solr. However when I execute the command python manage.py rebuild_index I get an error message saying Attribute error: type object 'BaseCommand' has no attribute 'option_list'. I was just wondering whether anyone knows of or has had this error before? -
Django bootstrap modal file upload form
Today Ive spent about 3 hours on the internet, looking for solution, but no luck. I want to have bootstrap modal (popup) and inside that modal i have form, to choose a number between 1-6 and upload picture file. So far i have these files: Views.py: SUJECTS = ["subject1", "subject3", "subject55",] @login_required def create_exam(request, letnik_id, classes_id, subject_id): response_data = {} if subject_id in SUBJECTS: path = letnik_id + '/' + classes_id + '/' + subject_id form = ExamForm(request.POST or None, request.FILES or None) if form.is_valid(): exam = form.save(commit=False) exam.exam_user = request.user exam.exam_path = path exam.exam_file = request.FILES['exam_file'] file_type = exam.exam_file.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'error_message': 'File must be PNG, JPG ali JPEG', } return ?? if Exam.objects.filter(exam_path=path, exam_number=exam.exam_number): context = { 'form': form, 'error_message': 'Exam already exists!', } ??return?? exam.save() return redirect('subject_id', letnik_id=letnik_id, classes_id=classes_id, subject_id=subject_id) context = { "form": form } return render(request, 'exam_form.html', context) raise Http404("Site does not exist")` and i have exam_form.html: <!-- Modal --> <div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">&times;</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title" id="myModalLabel"> Dodaj Test </h4> </div> <!-- Modal … -
Saving file from URLField to ImageField
I'm trying to download my file from URLField and download it to ImageField. What i get is error 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte Unicode error hint The string that could not be encoded/decoded was: �PNG model: image = models.ImageField(upload_to='posts/', blank=True) image_url = models.URLField(null=True, blank=True) def save(self, *args, **kwargs): if self.image_url: result = urllib.request.urlretrieve(self.image_url) self.image_url = '' self.image.save( os.path.basename(self.image_url), File(open(result[0])) ) super(Post, self).save() -
django oscar model customization : model change is not reflected while makemigrations
I am trying to customize Products and few other models in the catalogue app following the documentation. I have forked catalogue app (to myproject/boscar/catalogue) as per documentation documentation and my updated boscar/catalogue/models.py: from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): is_active = models.BooleanField(default=False) from oscar.apps.catalogue.models import * I have already included the modified catalogue app, in the INSTALLED_APPS in settings.py as an argument for get_core_apps function. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django.contrib.sites', 'django.contrib.flatpages', 'bmigrate', 'compressor', 'widget_tweaks', 'boscar' ] + get_core_apps(['boscar.catalogue']) Migrations are automatically copied to my local app when I executed this command manage.py oscar_fork_app catalogue boscar. My issue is when I execute the makemigrations command (python "manage.py makemigrations boscar"), it shows "No changes detected in app 'boscar'". But I already made a change to add is_active field in product table. -
Deploy with heroku
So I am on the last step of deployement with heroku, everything is ok the files, the installations, etc., but when I did heroku open it shows me this: "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details." I checked the logs with cmd and here is what it shows: So ! am I missing something ? -
Form in different blocks in django template does not work
Hi i am creating a form page but I design the layout in different template so I put the forms in different blocks. To understand better, this is how it looks: template {% block top_content %} <form> <input type="text" name="title" /> {% endblock %} {% block middle_content %} <input type="text" name="discription" /> {% endblock %} {% block bottom_content %} <button type="submit">Submit</button> </form> {% endblock %} This problem here is I can not submit the form. I think maybe because I separate them in different blocks, but this helps me for the design of different forms I have. Is there are way that this will work even if they are in different blocks? -
Django, serving static files with nGinx gives error 404
I can't serve static files through nGinx and I am getting 404 instead. I can see the error (shown in the error.log), I just can't see how to fix it. urls.py urlpatterns += patterns('', ( r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static'} )) settings.py STATIC_ROOT = os.path.join(PROJECT_DIR, "staticfiles/") STATIC_URL = '/static/' DEBUG=False (did a collectstatic and all static files are now in 'staticfiles/') nginx configuration server { listen 80; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/project/project/project/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/home/project/project/project.sock; } } base.html {% load staticfiles %} <link rel="stylesheet" href="{% static '/css/main.css' %}"> and this is the log error.log 2017/04/09 10:57:40 [error] 4719#4719: *182 open() "/home/project/project/project/staticfiles/static/images/home-lock.png" failed (2: No such file or directory) ("static/" is added in the static url and I can't see why) -
Django translating choice fields
I've got some models like this: class Payment(models.Model): class Status(IntEnum): open = 0 balance = 2 closed = 1 status = models.IntegerField(choices=enum_to_choices(Status), default=0, verbose_name=_("Status")) I'm using a enum to denote my choices and to use them throughout other parts of my application. I'm converting these to tuples to use in choice fields with the following code: from django.utils.translation import ugettext_lazy as _ def enum_to_choices(enum): x = tuple([(x.value, _(x.name.replace("_", " "))) for x in enum]) return x The conversion part of the code works, i can use these fields as choices but the translation doesn't work, it doesn't show up in my translation files. If i change the parameter to uggettext_lazy with a static string like "open" it does show up. What's going on here? -
Change TimeField and DateField format in views
I have a very basic django model: class Topic(models.Model): day = models.ForeignKey(Day) time = models.TimeField(choices=CHOICE_TIME) topic = models.CharField(max_length=255) So if I access the object's day and time I get these results: >>> topic = Topic.objects.all()[5] >>> print topic.day 2017-03-13 >>> >>> >>> print topic.time 14:00:00 I need to use the day in 9 April 2017 format and time in 12 hours format 2 PM inside the views. How can I solve this? All the answers I found was for django templates, but I need it in views. -
Can the Django development server be started programmatically?
I'm trying to start the django development server from another module in my package. My module can import manage.py, and I want to execute the equivalent of manage.py runserver without using subprocess or anything of that sort (why? see below). Currently the best solution I could come up with is to use subprocess: def run_with_default_settings(): import inspect import subprocess currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) subprocess.Popen(['python', 'manage.py', 'runserver'], cwd=currentdir) However this solution seems to me rather overcomplicated, and more importantly it is not platform independent (for example if someone has both python 2 and python 3 and python is defined as python 3; or if python is not defined in the environment PATH... etc.). I couldn't find any solutions online, and every way I tried to run execute_from_command_line() failed miserably. Any ideas? -
Having trouble implementing _str_() method and making it run in the cmd
I firstly wrote down the method to make the object more human friendly to read but it does not work when I run my object in cmd. Just was after I ran the django built in API. python manage.py shell . Yet it still gives this result back when I run Question.objects.all() when I run it, it returns <QuerySet [Question: Question object]> Where my result should return <QuerySet [<Question: What's up?>]> . Please help me resolve this issue. import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def _str_(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def _str_(self): return self.choice_text -
Is there anything wrong with way I am using django-smart-selects? Why am I not able to make a ModelForm?
I am using django-smart-select. I want a form for my Location model which allows selection of continent based on which the Country will appear. After supplying the users address, the form needs to be submitted. This is what I have done. # myapp/models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey class Continent(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Country(models.Model): name = models.CharField(max_length=20) continent = models.ForeignKey(Continent) def __str__(self): return self.name class Location(models.Model): newcontinent = models.ForeignKey(Continent) newcountry = ChainedForeignKey( Country, # the model where you're populating your countries from chained_field="newcontinent", # the field on your own model that this field links to chained_model_field="continent", # the field on Country that corresponds to newcontinent # show_all=False, # only shows the countries that correspond to the selected continent in newcontinent ) my_address = models.CharField(max_length=20) #myapp/forms.py from myapp.models import Location from django.forms import ModelForm class LocationForm(ModelForm): class Meta: model = Location fields = ['newcontinent', 'newcountry', 'my_address'] #myapp/templates/myapp/addLocationForm.html {% extends 'registration/base.html' %} {% block title %}Add a new location{% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit"> Post </button> </form> {% endblock %} #myapp/views.py def addlocation(request): if request.POST == "POST": form = LocationForm() if form.is_valid(): form.save() … -
How to use the context variables passed from Django in javascript?
I am having a method in views.py as follows: def index(self, request): initial = get_initial() context = {"context" : initial_topics} template = loader.get_template('index.html') return HttpResponse(template.render(context, request)) How do I access the "context" dict in javascript ?? Like in my $(function(){}); -
TypeError at /admin/ 'set' object is not reversible and argument( ) to reverse must be a sequence
My app was working perfectly but when I tried the admin url, this error occurred.I can access every page of the website except for the admin page. My project is mini mini.urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('main.urls')), url(r'^', include('signup.urls',namespace='signup')), ] main.urls.py from django.conf.urls import url,include from . import views urlpatterns = [ url(r'^$', views.index,name='index'), ] signup.urls.py from django.conf.urls import url,include from . import views urlpatterns = { url(r'^signup/$', views.register, name='register'), url(r'^login/$', views.login_user, name='login'), url(r'^userpage/$', views.user_page, name='userpage'), url(r'^upload/$', views.upload_file, name='upload'), url(r'^logout/$', views.logout_user, name='logout'), url(r'^(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9] {12})/$', views.doc_detail, name='detail'), url(r'^(?P<uuid>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9] {12})/decrypt/$', views.doc_decrypt, name='docdecrypt'), } The error I ran into at /admin/ TypeError at /admin/ 'set' object is not reversible Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.10.5 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\urls\resolvers.py in _populate, line 196 Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.0 Python Path: ['C:\\Users\\user\\Desktop\\django projects\\mini', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36- 32\\python36.zip', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python36- 32\\lib\\site-packages'] I tried running my webapp in another pc so I ran into the following error: TypeError at /admin/ argument to reversed() must be a sequence Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.10.5 Exception Type: TypeError Exception Value: argument … -
Django Redirect to Login Page and Back Again
I'm redirect a user that is not logged in to the Login page using: return redirect('login'). Having logged them in I want them to return to the view they were going to. The URL then need to return to is: url(r'^proposal/(?P<qid>[0-9a-zA-Z]+)/$', views.quote, name='proposal') How do I do this? -
Constructing Dictionaries of dictionary in python
def home(request): context = populate_user_context(request, user.username) val=amqp.consumer() return render(request, "home.html", context, "Content-type:text/HTML", 200, None) def populate_user_context(request,username): user = User.objects.get(username=username) context={'first_name':(user.first_name or None), 'last_name':(user.last_name or None), 'email':(user.email or None) } return context When the function home is called. It builds up the context then calls consumer function. The consumer function returns a dictionary. If it returns a dictionary then i should call it again until it returns none(This part is not yet coded). Finally i have to add this to context and render to home.html. Each dictionary is like {'a' : val1, 'b': val2}. Since i dont know how many dictionary it may return. What is the best way to get the dictionaries add to the context and render to home.html page. Earlier the question was not clear so i have edited. -
Nginx rewriterule is ignored
I have a Django / production server with nginx as a front server. Here are the principles: if the domain name is not exactly www.mywebsite.com then redirect to www.mywebsite.com if the URL begins by static or public/profiles then pass to the Apache server (the alias is apache) otherwise pass to the Python server (the alias is mywebsite_python) Here's my configuration for those rules: server { listen *:80; server_name "~^.*mywebsite\..*"; index index.html index.htm; rewrite ^ http://www.mywebsite.com$request_uri permanent; } server { listen *:80; server_name www.mywebsite.com; index index.html index.htm; location ~ ^/(static.*|public/profiles/) { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Server $host; proxy_pass http://apache$uri; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Server $host; proxy_pass http://mywebsite_python/; } } But the second rule is ignored, and it's always the last one (pass to the Python server (the alias is mywebsite_python)) which is applied. What am I missing? -
Adding permissions to API with a custom auth backend
I am working on a chat website using Djangorestframework, and the way of submitting a message in it is done using a `GenericAPIView` and the serializer of the `Message` model. The MessageSerializer gets a User and the content, and I want to restrict submitting messages in the name of a user to only that user, so users won't be able to post messages in the name of other users. The way I thought was best is to check inside the `post` method of the `GenericAPIView` for a match between the author of the message and the currently authenticated user. The problem is that I have a custom auth backend, so for some reason, `request.user` is `AnonnymousUser`, even when I set the default authentication of DRF to `SessionAuthentication`, I still get the same results. Is there a better way to achieve this? Or is there something I am doing wrong? I would really appreciate the help. -
AttributeError: 'WSGIRequest' object has no attribute 'data'
I am studying Django form without model. Next stage will be form with model and finally form + model + crispy Right now I am stopped by request.data The root cause is request does not has attribute data (Pdb) dir(request) ['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_body', '_encoding', '_files', '_get_files', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'csrf_processing_done', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', 'read', 'readline', 'readlines', 'resolver_match', 'scheme', 'session', 'upload_handlers', 'user', 'xreadlines'] base.py: 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR.path('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', ], }, }, ] forms.py: from django import forms class PersonDetailForm(forms.Form): name = forms.CharField(max_length=100) age = forms.IntegerField() views.py: class ColorStudyView(View): template_name = 'colors/study.html' form_class = PersonDetailForm def get(self, request, format=None): form = self.form_class return render( request, self.template_name, {'form': form} ) def post(self, request, format=None): form = self.form_class(request.data) if form.is_valid(): return HttpResponse("Good … -
No module named <app_name>
So, I made a chat app using django-channels in a separate project and now I am copying it into the main project. This is what is happening. when I run ./manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7f695c1cfde8> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/channels/management/commands/runserver.py", line 40, in inner_run self.channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER] File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 53, in __getitem__ self.backends[key] = self.make_backend(key) File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 48, in make_backend routing=routing, File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 80, in __init__ self.router = Router(self.routing) File "/usr/local/lib/python2.7/dist-packages/channels/routing.py", line 25, in __init__ self.root = Include(routing) File "/usr/local/lib/python2.7/dist-packages/channels/routing.py", line 201, in __init__ self.routing = Router.resolve_routing(routing) File "/usr/local/lib/python2.7/dist-packages/channels/routing.py", line 75, in resolve_routing raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e)) django.core.exceptions.ImproperlyConfigured: Cannot import channel routing 'website.routing.channel_routing': No module named myWebsite I know this is some error with django not recognising my module , but in other places it's recognising so why not here The culprit code, the reason why I am stuck here for 2 days : website/website/routing.py from channels import include from myWebsite.routing import websocket_routing, custom_routing channel_routing = [ # Include sub-routing from an app. include(websocket_routing, path=r"^/chat/stream"), include(custom_routing), ] website/myWebsite/routing.py from channels import route from .consumers …