Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / combinig DetailView FormMixin and Function based views
I try to make a reddit clone with django. The problem is I can't combine DetailView and a function based view. I can create a post and comments to specific posts but couldn't make nested comments. I created the logic but couldn't render it. How should I render nested comments ? I can't get the data wit get_context_data views.py class EntryDetail(DetailView, FormMixin): template_name = 'post_detail.html' model = Post form_class = CommentForm def get_success_url(self): return reverse_lazy('post-detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(EntryDetail, self).get_context_data(**kwargs) context['post_object'] = Post.objects.filter(pk=self.kwargs.get('pk')) context['comments'] = Post.objects.get(pk=self.kwargs.get('pk'))\ .comments\ .all() return context def post(self, request, *args, **kwargs): form = self.get_form() p_object = Post.objects.get(pk=self.kwargs.get('pk')) if form.is_valid(): form.save(post=p_object.id) return redirect(reverse_lazy( 'post-detail', kwargs={'pk': p_object.pk})) def add_sub_comment(request, comment_id): comment = Comment.objects.get(pk=comment_id) if request.POST: form = SubCommentForm(request.POST) if form.is_valid(): form.save(comment_object=comment.id) return redirect('index') sub_comments = Comment.objects.filter(object_id=comment.id) ctx = {'sub_comments': sub_comments} return render(request, 'post_detail.html', ctx) urls.py urlpatterns = [ url(r'^$', EntryView.as_view(), name='index'), url(r'^new_post/$', EntryCreate.as_view(), name='new-post'), url(r'^post_detail/(?P<pk>\d+)/$', EntryDetail.as_view(), name='post-detail'), url(r'^sub_comments/(?P<comment_id>\d+)/$', views.add_sub_comment, name='sub-comment'), ] post_detail.html {% for comment in comments %} <div class="comment-per-style"> {{ comment.entry_comment }} {% for subcomment in sub_comments %} <ul> <li>{{ subcomment.entry_comment }}</li> </ul> {% endfor %} </div> <form action="{% url 'sub-comment' comment.id %}" method="post"> {% csrf_token %} <input id="entry_comment" type="text" name="entry_comment" maxlength="100" required … -
Testing views in Django, need a hand
I'm trying to understand how django works,but I have a question in views. With the code below def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) I understand the dictionaries but I do not know why {'posts': posts} is a dictionary with the same word and the value does not have quotation marks. When I use dictionaries I use something like: hello = {'my_key': 'this is text', 'my_key2': 2017 } {'posts': posts}, in this example post is shown twice and the second, I mean the value does not have quotation marks. can anyone explain me please? -
Reverse for viewname with arguments '(1,)' not found
Attempting to start the server and getting following exception (starting server leads to polls/index.html page): django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['$(?P[0-9]+)'] If I remove the following line fron index.html, the error is removed. But I don't get what the issue is. Even the ide prompts the current data. Found similar questions where the issue was with incorrect number of arguments which isn't the case with this. Please help. Error line: {% url 'polls:detail' q.id %} index.html {% for q in latest_question_list %} <li><a href="{% url 'polls:detail' q.id %}">{{ q.question_text }}</a></li> {% endfor %} urls.py app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>[0-9]+)', views.detail, name='detail'), ] views.py def index(request): latest_question_list = Question.objects.order_by('pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): return HttpResponse(question_id) -
Is there a way to add a ForeignKey to the Site model in Django Sites Framework?
This answer shows the inverse of what I'm looking for because it allows one Site to have many Asset objects: from django.contrib.sites.models import Site class Asset(models.Model): site = Models.ForeignKey(Site) Is there a way to add the ForeignKey field to the Site model, such that one Asset can have many Site objects? Something like this (non-working) code: from django.contrib.sites.models import Site class UpdatedSite(Site): asset = models.ForeignKey(Asset) I understand that I could use a ManyToManyField but in my case one Site object will never have multiple Asset objects. -
Why is gunicorn displaying an extra process?
I have a gunicorn web server on my django app in my docker container and my gunicorn config is: bind = '0.0.0.0:8001' loglevel = 'debug' errorlog = '-' accesslog = '-' preload = True reload = True workers = 2 My gunicorn command is: gunicorn -c gunicorn_conf.py project.wsgi:application I am expecting it to only show 2 processes when I hit ps aux in the container or docker top but it turns out that it has three like the one below USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 21756 2600 ? Ss 21:48 0:00 /bin/bash /usr/src/app/entrypoint.sh root 6 0.0 1.0 97424 21860 ? S 21:48 0:01 /usr/local/bin/python /usr/local/bin/gunicorn -c gunicorn_conf.py project.wsgi:application root 11 2.7 3.2 310404 65560 ? Sl 21:48 1:20 /usr/local/bin/python /usr/local/bin/gunicorn -c gunicorn_conf.py project.wsgi:application root 12 2.7 3.2 310408 65572 ? Sl 21:48 1:20 /usr/local/bin/python /usr/local/bin/gunicorn -c gunicorn_conf.py project.wsgi:application -
Django: Prevent Data Repetition
This is how my model looks like, class Question(models.Model): .... & another one class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) .... I'm trying the filter out those questions which have answer, I tried the simplest way, i.e. result = Question.objects.order_by('-answer')[:10] As it should it's repeating the question in results if they have more than 1 answer which I don't want. I tried distinct() but it's not working. I just want a question to appear once even if it has multiple answers. How can I prevent the repetition of Questions in results if they have multiple answers? What is the best way of doing it? Please helpme. Thank You :) -
Django join multiple tables
I have the following three models. (I have removed unnecessary fields for clarity) class Product(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class MRFDetails(models.Model): mrf_no = models.AutoField(primary_key=True) customer_id = models.ForeignKey(CustomerDetails) product_id = models.ForeignKey(Product) machine_no = models.CharField(max_length=255) class MRFStatus(models.Model): mrf_no = models.ForeignKey(MRFDetails) worker_id = models.CharField(max_length=255) I want to get the result as it's expected to be given from the following SQL query. Simply to get name form product table for the values I get from MRFStatus. SELECT `SandD_mrfstatus`.`mrf_no_id`, `SandD_mrfdetails`.`mrf_no`, `SandD_mrfdetails`.`product_id_id`, `SandD_product`.`product_id`, `SandD_product`.`name`, `SandD_product`.`end_product_name` FROM `SandD_mrfstatus` INNER JOIN `SandD_mrfdetails` ON ( `SandD_mrfstatus`.`mrf_no_id` = `SandD_mrfdetails`.`mrf_no` ) INNER JOIN `SandD_product` ON ( `SandD_mrfdetails`.`product_id_id` = `SandD_product`.`product_id` ) WHERE `SandD_mrfstatus`.`status` = 0 ORDER BY `SandD_mrfstatus`.`status` ASC, `SandD_mrfstatus`.`modified_datetime` DESC This is what I have tried gg = MRFStatus.objects.all().filter(Q(status__contains=0)).order_by('status','-modified_datetime').select_related() How can I get the values that are there in MRFDetails and Product. print gg.values() gives the values related to MRFStatus table only. -
how to pass language between templates in django admin
I 'm overriding django-admin templates to add a language choice links. I added this: {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <a href="/{{ language.code }}{{ request.get_full_path|slice:'3:' }}" class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}" lang="{{ language.code }}"> {{ language.name_local }} </a> {% endfor %} in both base_site.html and login.html. They work fine The problem is that I always get the default language in the dashboard. For example: If I choose Frensh in the login page, the login page gets translated into frensh but after I login, I find the dashboard and other pages in the default language. How can I fix this, in order to display the dashboard in the language chosen from the login page -
Django - JSON file to DTL and JavaScript
I am trying to read a JSON file and pass its content to my template like this: with open('Directory_To_Json', "r") as data: content = json.load(data) return render(request, 'Displayer/index.html', {'Content': content}) It works, but I also want to be able to work with the same JSON inside of my javascript. I tried it like this: var jsonData = JSON.parse("{{Content}}"); But there is an error at the second position, although the JSON itself is valid. (I tried adding the "safe" modifier as well) I guess it's because I pass it the json.load output, which is formated to work with Python. But how can I pass it the raw json file content? Thanks in Advance -
Python can't read the environment variable with Supervisor
when I run sudo -E supervisor reread/reload I have the command defined in the [program:site] section to launch the gunicorn.conf.py /etc/supervisor/conf.d/weather.conf [program:site] directory=/home/nhcc/campus-weather-station/weather_station command=/home/nhcc/venv/weather_station/bin/gunicorn -c /home/nhcc/campus-weather-station/weather_station/gunicorn.conf.py -p gunicorn.pod weather_station.wsgi gunicorn.conf.py # -*- coding: utf-8 -*- # /usr/bin/python3 import os bind = "{}:8080".format(os.environ['DJANGO_WEATHER_STATION_HOST']) worders = (os.sysconf('SC_NPROCESSORS_ONLN') * 2) + 1 loglevel = 'error' command = "WTR_VENV/gunicorn" pythonpath = "$PROJECT/weather_station" it will showed up the error . I set DJANGO_WEATHER_STATION_HOST in the /etc/profile.d/project.sh project.sh export DJANGO_WEATHER_STATION_HOST=the_host_ip After reloading it but in vain. I also set in the ~/.profile But still got the error. -
GeoDjango Distance object to serializer
I want to get the distance as a return values how can I convert the Distance object to decimal value. My query query = Model.objects.filter(location__distance_lte=(search_location, D(m=distance)) ).annotate(distance=Distance('location', search_location) ).order_by('distance') Serializes class ModelSerializer(serializers.ModelSerializer): distance = serializers.FloatField() class Meta: model = Model fields = ('id', 'name', 'image', 'distance',) I am getting an error float() argument must be a string or a number, not 'Distance' How can I do it. ? -
How To retrieve ArrayField data in django query?
I have a model with an ArrayField as: class Item: static_data = ArrayField( models.CharField(max_length=120), blank=True ) Now I want to retrieve only the First Element of the Array in a select query using django model. Is it possible to do so? If its possible how do I achieve it. -
All creation date of all users which are customers
In a web application, it is possible to create User and CustomerProfile. A user could be an employee and a customer. I could find the creation date with >> cust = CustomerProfile.objects.get(pk=100) >> cust.user.date_joined >> datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) I know I can find all users with User.objects.all(). How could I find all users which are not employees? Be aware that User is the parent class of CustomerProfile. -
Django 1.11 - templates folder in project directory
I'm struggling to get the following working: I would like to have a 'general' templates folder for non-app-specific html in the directory of my project, akin to the static folder for non-app-specific static files. My current structure looks like this: |- my_app/ |- dashboard/ |- static |- dashboard/ |- css/ |- ... |- templates |- dashboard |- index.html |- ... |- urls.py |- views.py |- landing/ |- static |- landing/ |- css/ |- ... |- templates |- landing |- index.html |- ... |- urls.py |- views.py |- my_app/ |- static/ |- my_app/ <-- no problem loading these |- css/ |- ... |- templates |- my_app <-- unable to load these |- boilerplate.html |- settings.py |- ... |- manage.py My current convention is that if the html or static files are in an app directory, they are specific to that app, if they are in the project (here my_app) directory, they are applicable across the whole project. My problem now is that when I try to load boilerplate.html (a snippet) into dashboard/index.html by stating {% include "my_app/boilerplate.html" %} in dashboard/index.html, it complains with: TemplateDoesNotExist at /dashboard My settings.py file, or at least the part I believe to be relevant is the … -
Django Database Migration
Hi have a django project a full project now I want to migrate to mysql from the default Sqlite3 which is the default database. I am on a Mac OS and I don't know how to achieve this process. Any one with a complete guide on how to make the switch would be appreciated. -
Why is there a string of garbled words about Django's URL?
enter image description here 麻烦用小白的角度来想哈,Thank you ! -
Multiple files through django model
Please help. I am Trying to add multiple files to my database using jquery(one file at a time). In my project each user must be able to upload multiple files. For some reason my code doesnt upload any files. Given below is my models.py file from django.contrib.auth.models import User def get_upload_path(instance, filename): return 'users/{0}/{1}'.format(instance.user.username, filename) class MusicCollection(models.Model): user = models.ForeignKey(User) document = models.FileField(upload_to=get_upload_path) def __unicode__(self): return self.user.username Could it be, the models is causing the problem? -
Multilingual model error messages aren't translated
I'm using Multilingual Models. The problem is that the errors messages doesn't get translated in the template. this is the multilingual forms.py from __future__ import unicode_literals import logging logger = logging.getLogger(__name__) from django.utils.translation import ugettext_lazy as _ from django.forms.models import BaseInlineFormSet from django import forms from . import settings class TranslationFormSet(BaseInlineFormSet): """ FormSet for TranslationInlines, making sure that at least one translation is required and that sensible default values are selected for the language choice. """ def clean(self): """ Make sure there is at least a translation has been filled in. If a default language has been specified, make sure that it exists amongst translations. """ # First make sure the super's clean method is called upon. super(TranslationFormSet, self).clean() if settings.HIDE_LANGUAGE: return if len(self.forms) < 2 and not any(self.errors): raise forms.ValidationError( _('All translations should be provided.') ) .................... for example : _('All translations should be provided.') message doesn't get translated in the template. I don't know what's wrong, since the use of _(..) is there. Any help? -
NoReverseMatch at / (reverse logout)
I get this error on the homepage of my website: NoReverseMatch at / Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. Here is my urls.py: from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from profiles import views as profiles_views from contact import views as contact_views from checkout import views as checkout_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', profiles_views.home, name='home'), url(r'^about/$', profiles_views.about, name='about'), url(r'^profile/$', profiles_views.userProfile, name='profile'), url(r'^checkout/$', checkout_views.checkout, name='checkout'), url(r'^contact/$', contact_views.contact, name='contact'), url(r'^accounts/', include('allauth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root= settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) views.py: from django.contrib.auth.decorators import login_required from django.shortcuts import render #Create your views here def home(request): context = {} template = 'home.html' return render(request,template,context) def about(request): context = {} template = 'about.html' return render(request,template,context) @login_required def userProfile(request): user = request.user context = {'user': user} template = 'profile.html' return render(request,template,context) the traceback: File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers \exception.py" in inner 39. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers \base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adila\Documents\tryFOUR\src\profiles\views.py" in home 8. return render(request,template,context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) … -
Django and Pymongo connection not getting established
I am running an application where I need to have connection between the MongoDB and the Django application. I am running the application with the command: python manage.py runserver I am using Python 3.5 on windows 10 OS Here is my settings.py file part where I am trying to attempt the connectivity between the MongoDB and Django from pymongo import MongoClient # MONGO_DATABASE_NAME = 'testdb' # MONGO_HOST = 'localhost' # MONGO_PORT = 27017 MongoClient("mongodb://localhost:27017") SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' The part where I am getting the connection error is : if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: # print (form.cleaned_data['for_analysis']) mongo = API_Mongo() mongo.content = form.cleaned_data['for_analysis'] mongo.save() logger.debug('Text Data saved to Mongo DB') data = form.cleaned_data['for_analysis'].encode("utf-8") The error occur at mongo.save() The following is the error: Exception Type: ConnectionError at /analyze/ Exception Value: You have not defined a default connection My complete TraceBack is available here: TraceBack -
Class Based Views (CBV), CreateView and request.user with a many-to-many relation
Based on the examples from https://docs.djangoproject.com/en/1.11/topics/class-based-views/generic-editing/#models-and-request-user - but with a many-to-many relation instead of a foreign key relation: models.py from django.contrib.auth.models import User from django.db import models class Author(models.Model): name = models.CharField(max_length=200) owners = models.ManyToManyField(User, related_name='owners_') views.py from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] def form_valid(self, form): form.instance.owners = self.request.user return super(AuthorCreate, self).form_valid(form) Will output "<Author: test>" needs to have a value for field "id" before this many-to-many relationship can be used. How to avoid this? -
Django Haystack - unable to build solr schema
I got following error when I tried to build solr schema: (my_env) pecan@tux ~/Documents/Django/mysite $ python manage.py build_solr_schema Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 29, in handle schema_xml = self.build_template(using=using) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/haystack/management/commands/build_solr_schema.py", line 57, in build_template return t.render(c) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/backends/django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "/home/pecan/Documents/Django/my_env/lib/python3.4/site-packages/django/template/context.py", line 287, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than Context. Maybe these informations will be useful: mysite/settings.py file: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '****' # SECURITY WARNING: … -
Django Admin Proxy Model Permission Django 1.11
I have created a model in one app and created a proxy model in another app. Now I want to give only view permission to a group of users for this proxy model in Django admin. #core app class Dress(models.Model): name = models.CharField("Nome", max_length=80) #enza app class EnzaDress(Dress): class Meta: proxy = True In permission gird of Django user group record page, I did not see any entry to give view permission for this proxy model(EnzaDress) in Django admin. My Django version is 1.11.5 -
Server not running
I'm a beginner in programming and I am trying run finished project in pycharm. However on trying to run the server. I was getting the following error. So can someone please explain? "C:\Program Files\JetBrains\PyCharm 2017.2.2\bin\runnerw.exe" C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\python.exe E:/download/manage.py runserver 8000 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0330ED68> Traceback (most recent call last): File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-1.11.5-py3.6.egg\django\apps\config.py", line 120, in create mod = import_module(mod_path) File "C:\Users\Jaloliddin\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'blog' -
How can I authenticate user using Django websockets?
I try to create a chatbot. Every user can create an account and authenticate using Tokens. This is done in Django Rest Framework. After creating an account every user has own ID in PostgreSQL database. However chat is based on a websockets. I wonder how can I set session in websockets because I need to know which user sends message. So it seems to me that the best solution would be to have the same ID using both DRF and websockets. Or maybe am I wrong? I try in the way shown below but without positive results. @channel_session_user_from_http def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) @channel_session_user_from_http def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) # @enforce_ordering @channel_session_user_from_http def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Can we start?' }) }) @channel_session_user_from_http def ws_disconnect(message): Group("chat").discard(message.reply_channel)