Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect to test database after upgrading to django 3.1
I am trying to migrate a django app from 3.0.11 to 3.1. I can run the app without any issues. But I cannot run tests anymore. The following error is thrown when running python manage.py test django.db.utils.ConnectionDoesNotExist: The connection e doesn't exist This is from my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config("DB_NAME", default='postgres'), 'USER': config('DB_USER', default='postgres'), 'PASSWORD': config('DB_PASSWORD', default='postgres'), 'HOST': config('DB_HOST', default='postgres'), } } Full stacktrace: Creating test database for alias 'default'... Destroying test database for alias 'default'... Traceback (most recent call last): File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/db/utils.py", line 172, in ensure_defaults conn = self.databases[alias] KeyError: 'e' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/test/runner.py", line 698, in run_tests self.run_checks(databases) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/test/runner.py", line 636, in run_checks call_command('check', verbosity=self.verbosity, databases=databases) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = … -
Previewing images using Django
I have a html,css and js app that I ported to Django and I want to preview an image before upload. A dropdown form allows users to select an option that will then display the image onto the screen before upload. I did this through javascript by setting img src = "" to empty and then when the user selected an option from the dropdown menu, javascript set the img src path i.e if user selected car from menu then js would set img src=images/car.png and display it. function displayImage(imgValue){ if (imgValue == 'car') { previewImage.setAttribute("src", "images/car.png"); previewDefaultText.style.display = "none"; previewImage.style.display = "block"; } else if (imgValue == 'location') { previewImage.setAttribute("src", "images/newyork.jpg"); previewDefaultText.style.display = "none"; previewImage.style.display = "block"; .... .... } The issue is that the JS isn't setting the path of the img src in Django. Can I do this through JS or will it require to rewrite in a more Django/pythonic way? Note: w/o the use of ajax. -
Convert multiple texts with python markdown in django views
I have a blog that uses markdown. I am trying to convert it to HTML in views.py with python markdown. For individual posts, this code works: def detail_view(request, slug): md = markdown.Markdown() post = get_object_or_404(Post, slug=slug) postcontent = md.convert(post.md_text) context = {...} return render(request, 'details.html', context) However, applying the same logic to a view meant to show multiple posts fails: def home_view(request): posts = Post.objects.order_by('-id') md = markdown.Markdown() for markdown in posts: postcontent = md.convert(posts.md_text) context = {...} return render(request, 'home.html', context) What would I need to change to convert the text_md field(s) of my Post model in this view? Thanks in advance! -
Saving form data in the database
Hello I am new in Django and I have created an available house posting form but I cannot store the entered data in the database. I used if form.is_valid and form.cleaned_data please I need help my code: views.py def public(request): form = PublicationForm() if request.method == 'POST': form = PublicationForm(request.POST, request.FILES) if form.is_valid(): first_name=form.cleaned_data['first_name'] last_name=form.cleaned_data['last_name'] agency_name=form.cleaned_data['agency_name'] city=form.cleaned_data['city'] categories=form.cleaned_data['categories'] status=form.cleaned_data['status'] phone_number_1=form.cleaned_data['phone_number_1'] phone_number_2=form.cleaned_data['phone_number_2'] description=form.cleaned_data['description'] image_one=form.cleaned_data['image_one'] pub = Publication.objects.create( first_name=first_name, last_name=last_name, agency_name=agency_name, city=city, categories=categories, status=status, phone_number_1=phone_number_1, phone_number_2=phone_number_2, description=description, image_one=image_one ) pub.save() return HttpResponse("Publication réussie") else: form = PublicationForm() return render(request, 'pub/public.html', {'form':form}) This is my template views I used the django-crispy-form module public.html <form method="POST" enctype="multipart/form-data " class="form-block "> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <div class="col-md-4 mb-3"> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }} "></label> {{ form.first_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.last_name.errors }} <label for="{{ form.last_name.id_for_label }} "></label> {{ form.last_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.agency_name.errors }} <label for="{{ form.agency_name.id_for_label }} "></label> {{ form.agency_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.city.errors }} <label for="{{ form.city.id_for_label }} "></label> {{ form.city|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.categories.errors }} <label for="{{ form.categories.id_for_label }} "></label> {{ form.categories|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.status.errors }} <label for="{{ form.status.id_for_label }} "></label> … -
How Retrieving a full tree data in Django Self Foreign Key?
I insert 3 records Electronics Null Mobile 1 Iphone 2 class Category(models.Model): name = models.CharField(max_length=160) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) if i search Iphone how to get all related data Example: Category.object.filter(name='Iphone') Result want all parent data ex: Electronics Mobile Iphone -
Linking ParentalKey to Abstract class and all subclasses in Wagtail
I am setting up a website in Wagtail. I have Author snippets which include author information. Each page (BlogPage) can be related to multiple Authors (via an AuthorOrderable). I am now trying to add a new Page type, so I have created an abstract superclass for Authors to link to, however I get the following error: AttributeError: type object 'BlogPage' has no attribute 'author_orderable' class AbstractPage(Page): class Meta: abstract = True author_panels = [ InlinePanel('author_orderable', label="Authors"), ] class BlogPage(AbstractPage): #Some fields- authororderable is not listed here class AuthorOrderable(Orderable, models.Model): page = ParentalKey('AbstractPage', on_delete=models.CASCADE, related_name='author_orderable') author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='+') @register_snippet class Author(models.Model): #Some fields -
Django to Heroku error: ModuleNotFoundError
I keep getting this error when deploying a Django app to Heroku via the Heroku CLI gunicorn the_weather.wsgi Traceback (most recent call last): File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\MARTIN KALAX\AppData\Local\Programs\Python\Python38-32\Scripts\gunicorn.exe_main.py", line 4, in File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in from gunicorn.app.base import Application File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\app\base.py", line 11, in from gunicorn import util File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\util.py", line 9, in import fcntl ModuleNotFoundError: No module named 'fcntl' -
Can you explain easily what is the function of misaka in django?
I'm a beginner at Django. I want to learn about the function of misaka in Django. -
How to get the authentication token from http header in Python Django Project deployed in Windows Server 2019 IIS using httpPlatformHandler?
An internal Python Django project was deployed successfully at IIS using wfastcgi.py. Referring to Authentication using REMOTE_USER, this application can get the log-in domain user information using REMOTE_USER available in the request.META attribute. According to An unknown FastCGI error occurred: Python 3.7 +Djangorestframework #6216, Microsoft/PTVS had stopped supporting wfastcgi.py and recommended to use httpPlatformHandler, my project is migrated to IIS using HttpPlatformHandler v1.2 in Windows Server 2019. Application migration is success except the MIT Kerberos authentication part. With references to HttpPlatformHandler Configuration Reference, when forwardWindowsAuthToken is set to true, the token will be forwarded to the child process listening on %HTTP_PLATFORM_PORT% as a header 'X-IIS-WindowsAuthToken' per request. I have no ideas about how to get this header and its key of Windows Authentication Token. Also with references to How to get the authenticated user name in Python when fronting it with IIS HTTP PlatformHandler and using Windows auth?, I tried to test the program example in both Flask and Django, however, I still cannot figure out how to get the request.headers.key() in Python properly. Could someone provide any hints or advise on this matter please? -
Can we run both Socket Server and Socket Client on the same Django Server?
I have a Django Server work as 2 role: Socket Server and Socket Client. 1/ As a Socket Server, it work on local side, so some clients in same network can connect and receive event. 2/ As a Socket Client, it will connect (using Socket) to another Remote Server to receive events and forward that events to all local clients But when Socket Client receive events then emit to local clients by Socket Server, nothing happen (local clients can't receive that events). If I just emit, my local clients can receive the message. It seem Socket Server and Client can't working together. Here is some sample of my code: // Receive event from Remote Server self.__client__.on("event_msg", self.onEvent) // Forward event to local Clients def onEvent(self, package): self.__socketServer__.emitEvent(event="event_msg", data=package, to=None, room="123") The __socketServer__ is just an instance of SocketServer class, and it can work if just simple send/receive message in local network (not put in socket client event) I'm using python-socketio for both Server+Client -
how to find the no of identical items in a table?
i am developing a web app in Django,using python.i have two classes one for item and other one for item details.i would like to count the similar models in item details table and display it as total quantity for that model in item table. -
How can I use fixtures in tests when using multiple databases in Django?
I am trying to get my Unit Tests to work in Django, in combination with fixtures in a context with multiple databases. What works currently is both Unit Tests with fixtures and Unit Tests using multiple databases, but when I am using both in the same Unit Test, Django doesn't do anything and is stuck at loading the fixture. Code in Unit Test: class MyUnitTestCase(APITestCase): fixtures = (os.path.join(FIXTURE_DIR, "data.json"),) databases = {"default", "datamarts"} DB Router: from django.conf import settings class DBRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label in settings.DATABASE_APPS_MAPPING.keys(): return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) return "default" def db_for_write(self, model, **hints): if model._meta.app_label in settings.DATABASE_APPS_MAPPING.keys(): return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) return "default" def allow_migrate(self, db, app_label, model_name=None, **hints): return True def allow_relation(self, obj1, obj2, **hints): """ Mostly used to run the tests for the data marts database """ return True Note that fixtures is a very small file that normally loads within a second. When using both multiple databases and fixtures, it takes over an hour - and is still loading. It could possibly be something related to the DB Router, as a breakpoint in db_for_write keeps showing the same model over and over again. -
ReactJS Imports not working blank webpage
I am a beginner learning ReactJS and was trying to make a full-stack quiz web application using DjangoRestFramework+ReactJS and I am not seeing anything rendering to my webpage when I try using imports. I am not getting any error, but my web page is blank. Here is my App.JS. import { render } from "react-dom"; import HomePage from "./HomePage"; import GameJoinPage from "./GameJoinPage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <HomePage /> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); My Index.html <! DOCTYPE html> <html> <head> <meta charset="UTF-9"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Quiz App</title> {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> <link rel="stylesheet" type="text/css" href="{% static "css/index.css" %}" /> </head> <body> <div id="main"> <div id="app"> </div> </div> <script src="{% static "frontend/main.js" %}"></script> </body> </html> And my HomePage file import React, { Component } from "react"; import GameJoinPage from "./GameJoinPage"; import CreateRoomPage from "./CreateGamePage"; import { BrowserRouter as Router, Switch, Route, Link, Redirect} from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render(){ return ( <Router> <Switch> <Route exact path="/"><p>This is the home page</p></Route> <Route path="/join" component={GameJoinPage} /> <Route path="/create" component={CreateGamePage} /> </Switch> … -
Authenticaton Postgres error while using Docker Compose, Python Django and Gitlab CI
I use Gitlab CI to make pipeline with building Docker image with my Django app. I saved some .env variables to Gitlab variables. They are succesfully calling and working, but there is psycopg2.OperationalError: FATAL: password authentication failed for user I have checked all passwords and variables, they are correct. .gitlab-ci.yml image: docker:stable services: - docker:18.09.7-dind before_script: - apk add py-pip python3-dev libffi-dev openssl-dev gcc libc-dev make - pip3 install docker-compose stages: - test test: stage: test script: - docker build -t myapp:$CI_COMMIT_SHA . - docker-compose -f docker-compose.test.yml run --rm myapp ./manage.py test - docker-compose -f docker-compose.test.yml run --rm myapp ./manage.py check - docker-compose -f docker-compose.test.yml down -v -
Constantly get an error "no such table" whatever I do
I am pretty new to django and database management as well, therefore there is certainly a possibility that I do not understand some crucial things about them. I've been trying to solve this error by myriads of ways for a few days (It occured as a result of a declaration of a new field in existing model called Habit), I tried: resetting database with reset_db (django-extensions) flushing it with native django flush command (now I do understand that it was a wrong method) recreating a whole app in another virtual environment with creation of fresh databases faking migrations with --fake (out of desperation basically) manually changing fields in a db with sql browser deleting sqlite database manually and making migrations Here are my models: from django.db import models from django.utils import timezone from datetime import timedelta import datetime # Create your models here. class Day(models.Model): # Creating table for this model didn't cause any trouble date = models.DateField(auto_now_add=True) def __str__(self): return str(self.date) class Habit(models.Model): name = models.CharField(max_length=200) targ_init_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time()) targ_term_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time()) true_init_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time()) true_term_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time()) is_completed = models.BooleanField(default=False) day = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='habits') # --That New … -
Trying to configure Gunicorn and Django settings, getting this error: [curl: (52) Empty reply from server]
I'm setting up my production Django app on Ubuntu. First time doing so, I've already troubleshooted and solved my way out of previous errors, however when I test the socket for activation via CURL using this command curl --unix-socket /run/gunicorn.sock localhost, I receive this an error: curl: (52) Empty reply from server. I've tried adding flags -L -vv , doesn't seem to help my case here. gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Here is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=andres Group=www-data EnvironmentFile=/home/andres/alpha/env_var WorkingDirectory=/home/andres/alpha/stockbuckets ExecStart=/home/andres/alpha/stockbuckets/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ stockbuckets.wsgi:application [Install] WantedBy=multi-user.target status of gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (running) since Wed 2020-11-25 15:39:48 UTC; 17min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Nov 25 15:39:48 sb-django systemd[1]: Listening on gunicorn socket. Given how Gunicorn is up and running, I want to make sure everything works before moving onto the next production stages. Hopefully I could get some advice on how solve for curl: (52) Empty reply from server. When I check the logs for Gunicorn, seems like everything is working a-okay? Please let me know … -
Django debug testpage when application is active in a subpath
In the Django tutorial, a quick way to check if setup of the django application was successful is by visiting the debug testpage. If I create a django application on my server under a subpath instead of on the main url, this page does not seem to work. The url this testpage seems to function on is '/', and my server configuration strips the application name '/demo/', including the slash, resulting in ''. (which causes a 404, empty path not found) It's easy to create a custom testpage on an empty path instead of on slash like so: path('', views.index, name='index'), However, does the missing slash in my application configuration indicate an issue that should be solved? Or is the empty url path for my testpage a logical choice in this situation? -
Problems with data from django to html
My goal is to have the sum of elements in lista [] but gives me this error. Lista[] is composed of decimal numbers ValueError at / argument must be a sequence of length 3 My code : views.py def Home(request): assets = Post.objects.filter(Asset="BTC", Utente="1").values_list('Quantit') lista = [] for asset in assets: lista.append(asset) somma = sum(Decimal(lista)) return render(request, 'porttrack/home.html', {'lista': lista}) models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): Utente = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Asset = models.CharField(max_length=3) Quantit = models.DecimalField(max_digits=19, decimal_places=11) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) by printing out only lista[] without "somma", it's show a list like that: [(Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),)] Thanks for helping me -
Django-dsl-drf Exclude phrase query
I am working on integrating Elastic Search in my existing Django REST application. I am using the django-dsl-drf module provided in the link below: https://django-elasticsearch-dsl-drf.readthedocs.io/ In their documentation 'exclude' query param is provided. But the query only when we provide the full field value. search-url?exclude=<field-value For eg: If I have a value 'Stackoverflow' in field 'name'. I'll have to provide query param a ?name__exclude=Stackoverflow to exclude records having 'Stackoverflow' as name in the result. I would like to implement a search in such a way that when I provide 'over', I need to exclude these records, similar to ?name__exclude=over I checked the above tutorial, but I couldn't find it. Is there any work around so that I can exclude records, fields containing terms instead of providing full field value, which is also case-insensitive. Thanks a lot. -
Django annotate a Boolean if field value is into an external list
Imagine I have this Django model: Class Letter(models.Model): name = models.CharField(max_length=1, unique=True) and too this list: vowels = ['a', 'e', 'i', 'o', 'u'] I want to make a query over Letter annotating a boolean field, which will be True if name value is in vowels list, and False otherwise I made next query: from django.db.models import Value, F, BooleanField letters = Letter.objects.annotate(is_vowel=Value(F('name') in vowels, output_field=BooleanField())) However no matter what letters I analyze, the result is ALWAYS False What am I doing wrong in my query, and what is the correct way to achieve the desired result? Thanks in advance. -
How to pass database object id which initiated Django post save signal
I am trying to solve the following problem. I have django view which provide functionality to save object in database. After view will save the object i want to proccess some logic on saved object at once (e.g check similarity of some fields with another objects) I hear about django signals specially about post_save signal which i think will appropriate for my usecase. But for my usecase i need to pass object id which initiated execution of post_save signal. Is in django signals any built-in solution to extract this object id to futher passing it to receiver of signal function Hope will my pseudo code will give more ckarification app_view(receive and save data as django model object) post_save signal(receiver, id_of_object_initiated_execution) -
Python, Django: Cross-Saving possible?
Good evening, I would like to know, if there's a "cross-saving"-possibility between to models inside my django-application? For example: models.py class Person(models.Model): first_name = models.CharField() last_name = models.CharfFeld() age = models.IntegerField() value_person= models.IntegerField() date_created = models.DateField class Account(): name = models.CharField() description = models.Textarea() person = models.ForeignKey(Person, null=False, blank=False, on_delete=models.CASCADE) value_a = models.IntegerField() value_b = models.IntegerField() date_created = models.DateField forms.py: class UpdateAccountForm(ModelForm): class Meta: model = Account exclude = [ 'name', 'date_created', ] views.py: [...] account_db = Account.objects.get(id=pk) form = UpdateAccountForm(instance=Account) if request.method == 'POST': form = CreateAccountForm(request.POST, instance=Account) if form.is_valid(): form.save() *** Do something here return("Somehwere") [...] Now I'm asking myself, if it's possible - while updating the "Account" - to update the "Person" and - let's say for example - add one of the two "values_..." into the "value_person"? The connection should be there via the "ForeignKey", right? I think I should also mention, that I'm talking about my default database! I'm aware that this might be a bad example, but it's just so that I can understand the system behind this - hopefully existing - function! Thanks to all of you! -
Name is not defined while trying to get request.user to use in a form
I know this question was asked many times but I keep getting the same error with the solutions posted in stackoverflow. I am probably making a simple mistake but as a beginner, I don't realy see where is my mistake. Here is my forms.py: from django import forms from .models import * class AddMark(forms.Form): def __init__(self, user, *args, **kwargs): self.user = user super(AddMark, self).__init__(*args, **kwargs) teacher = Teacher.objects.filter(user = self.user)[:1] modules = Module.objects.filter(enseignants__in = (teacher)) desc = forms.CharField(label='Description') coef = forms.FloatField(label='Coefficient') max_mark = forms.FloatField(label='Max Mark') module = forms.ChoiceField(label='Module',choices=modules) and it seems like error comes from teacher = Teacher.objects.filter(user = self.user)[:1] -
How to get all self foreign key data in Django?
how to retrieve all related parent field data in Django REST API class Category(models.Model): name = models.CharField(max_length=160) description = models.TextField() meta_title = models.CharField(max_length=160) meta_keywords = models.CharField(max_length=160) meta_description = models.TextField() level = models.IntegerField(default=0) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) icon = models.ImageField(upload_to='category/') def __str__ (self): return self.name -
django.db.utils.DataError: integer out of range(Websockets-Django Channels)
I am deploying a django chat application built using django Channels. I have create a daphne.service file to run the daphne command. Following are its contents: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/path/to/my/workingdirectory ExecStart=/home//path/to/my/virtualenv/python /home/django/path/to/virtualenv/bin/daphne -b 0.0.0.0 -p 8001 myapp.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target The websocket connects when the page loads but as soon as I send a message, the socket closes. After checking the status of the daphne.service file I get the following: Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]:return self._execute_with_wrappers(sql, params,many=False, executor=self._execute) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: return executor(sql, params, many, context) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: return self.cursor.execute(sql, params) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: raise dj_exc_value.with_traceback(traceback) from exc_value Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: File "/home/ubuntu/django/virtualenv2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: return self.cursor.execute(sql, params) Nov 25 14:48:41 ip-172-31-34-249 daphne[1165]: django.db.utils.DataError: integer out of range Any ideas What could be wrong here? Thanks