Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can we edit the user profile without using forms.py in django?
How to create view for the registered user to edit there profile in the user dashboard using django ? Please provide the view . I have created the register profile without using the forms.py , Now I want to create the userprofile edit only without using forms.py. And Is it possible to submit the data again to the database. (Dont use forms.py) Accounts/views.py def register(request): if request.method == 'POST': #get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] #Check if passwords match if password == password2: #check username if User.objects.filter(username = username).exists(): messages.error(request,'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request,'That email is being used') return redirect('register') else: #looks good user = User.objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name) #login after register # auth.login(request, user) # messages.success(request, 'You are now logged in') # return redirect('index') user.save() messages.success(request, 'You are now registered and can log in') return redirect('login') else: messages.error(request,'passwords do not match') return redirect('register') else: return render(request, 'accounts/register.html') -
OperationalError at /admin/weather/city/
i am following this tutorial and it created migrations folder without any error but when i logon to localhost:8000/admin and click cities i get OperationalError at /admin/weather/city/ models.py from django.db import models # Create your models here. class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Meta: verbose_name_plural = 'cities' views.py import requests from django.shortcuts import render # Create your views here. def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=###' city = 'Las Vegas' r = requests.get(url.format(city)).json() city_weather={ 'city':city, 'temperature':r['main']['temp'], 'description':r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } context = {'city_weather': city_weather} return render(request,'weather/weather.html',context) after performing python manage.py makemigrations python manage.py migrate 0001_initial # Generated by Django 3.0.3 on 2020-03-18 02:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=25)), ], options={ 'verbose_name_plural': 'cities', }, ), ] then added below code in admin admin.py from django.contrib import admin from .models import City # Register your models here. admin.site.register(City) After several similar questions and answers i had deleted migration folder and again performed python manage.py makemigrations python manage.py migrate tried python manage.py migrate --run-syncdb too but all in vain getting the same error , please help stuck for … -
Django annotate string value
I'm trying to use the following SQL query in my the django query UNION query: 'transfer' AS transaction_type, And as using annotate i would use: annotate(transaction_type=Value('transfer', CharField())) But i keep getting this following error in my view : invalid literal for int() with base 10: 'transfer' I even tried annotate(transaction_type=Value('transfer', output_field =CharField())) but still got the same error How do i use string in annotate ? -
Django Method Not Allowed (POST) 405
Can anyone help me with this. I'm trying to get the value of my input in html by using javascript but when i ran my project it shows this. Method Not Allowed (POST) May you help me find what is the problem and how am i gonna solve this? url: from django.conf.urls import url,include from . import views from django.contrib.auth.decorators import login_required from django.views import View urlpatterns = [ url(r'^change-nameserver/$', login_required(views.bulkNSChange.as_view()), name='change_NS'), ] views: class bulkNSChange(GENERIC_PERMISSION_MIXIN,View): permissions_required = 'can_use_DNS_API' def post(self, request): context = { 'result': { 'bulkChange': False, } } body = json.loads(request.body) print body,'loaded' if body: assert type(body == dict) print 'eto po' log.info('PROCESSING CHANGE NS- {1} to {2}'.format(body['domain'], body['nameServer'])) context['result']['bulk'] = { 'bulkChange': True, 'bulkNS': 'YEAH' } return HttpResponse(json.dumps(context), content_type='application/json') js: function bulkUpdateNS(){ var prompt = confirm('Execute Bulk NS Changes? (This event is logged)') if (prompt){ var domain = document.getElementById('domain') var nameServer = document.getElementById('nameServer') var nsbody = { 'domain': domain.value, 'nameServer': nameServer.value } console.log(nsbody) $.ajax({ type: "POST", dataType: "json", url: "/domains/change-nameserver/", data: JSON.stringify(nsbody), success: function(result) { alert('Bulk Changing Domain NS started') }, error: function(err) { console.log(err) }, complete: function(){ domain.value ='' nameServer.value ='' $('#bulkChangeNSModal').modal('hide'); } }); } } -
How to use the Django DRF serializer for ManyToManyField
I'm trying to write a serializer for my models which has a ManyToManyField. My problem seems to be very similar to this example, but at this time I'm not interested in using a SlugField and nevertheless it's not clear to me what my problem is. models.py class Objective(models.Model): objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) def __str__(self): return self.objective_name class Assessment(models.Model): objective = models.ManyToManyField(Objective) date_completed = models.DateField(auto_now_add=True) serializers.py class AssessmentSerializer(serializers.ModelSerializer): objective = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Assessment fields = ['name', 'date_completed', 'objective'] class ObjectiveSerializer(serializers.ModelSerializer): class Meta: model = Objective fields = '__all__' From the DRF docs, I thought that the following POST would create an Assessment object where I already have two Objective objects with id's of 3 and 4 respectively. { "name": "Quiz 3", "objective": [ 3, 4 ] } However, this creates the Assessment object but there is no link between it and the Objectives. { "name": "Quiz 3", "date_completed": "2020-03-17", "objective": [] } Is my serializer incorrect, or am I using wrong syntax for the POST, or is there a different issue? -
Convert virtualenv project to pipenv Without a requirements.txt File
I've set up a DigitalOcean droplet with Ubuntu, python 3.6, and django 3.0. The instructions I used installed virtualenv. I'd like to change to pipenv, which is what I use in development. The answers I've seen say to set it up in the same directory as the requirements.txt file. I've never seen any such file. I'm new to django so I'm guessing it was used in older versions. I do have a projectXdir that contains projectX and projectXenv. ProjectX contains the actual project. ProjectXenv contains bin, include, lib, lib64, pyvenv.cfg, and share. The bin has the packages I've installed. Where do I run pipenv to set it up for the project? What do I get rid of afterwards? -
Unknown Command: 'manage.py' in runserver in Pycharm
I have an app I want to run in Django and when I run it or just try to test in in runserver in Pycharm, it gives me the "Unknown command: 'manage.py' manage.py@ATWM_Django > manage.py "C:\Program Files\JetBrains\PyCharm 2019.1.3\bin\runnerw64.exe" C:\Users\dbkar\Desktop\ATWM_Django\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.3\helpers\pycharm\django_manage.py" manage.py C:/Users/dbkar/Desktop/ATWM_Django Tracking file by folder pattern: migrations Unknown command: 'manage.py' Type 'manage.py help' for usage. Process finished with exit code 1 -
Mounted a local direcotry in my Docker image, but it can't read a file from that directory
I'm trying to build a docker container with MySql, Django, and Apache images. I have set up this docker-compose.yml ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3306" volumes: - my-db:/var/lib/mysql command: ['mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci'] web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" links: - web:web volumes: my-db: I would like to mount my docker Django image to a directory on my local machine so that local edits can be reflected in the docker container, which is why I have this volumes: - ./web/:/app in my "web" portion. This is the web/Dockerfile I'm using ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m … -
How do I correctly retrieve objects from a database using Django REST api?
I'm teaching my self how to use the Django REST api but I'm running into a JSONDecodeError. I'm trying to display posts depending on the user that is stored in the session. I'm storing the user username, password, and id in the session for later use. The JSONDecodeError is targeting the line with instruction posts = posts_response.json() when I look at the HTML error page Here's my views.py: posts_path = "http://127.0.0.1:8000/posts/" def index(request): if request.method=='GET': post_form = PostForm() posts_response = requests.get(posts_path) posts = posts_response.json() context = { 'post_form': post_form, 'post_list': posts, } return render(request, 'UserLanding/index.html', context) else: return render(request, "UserLanding/index.html") This is my viewsets: class PostView(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): query_set = self.queryset.filter(user=self.request.session['id']) return query_set class SubscriberView(viewsets.ModelViewSet): queryset = Subscriber.objects.all() serializer_class = SubscriberSerializer My registered urls: router = routers.DefaultRouter() router.register('posts', viewsets.PostView) router.register('users', viewsets.SubscriberView) And serializers: class SubscriberSerializer(serializers.ModelSerializer): class Meta: model = Subscriber fields = ('id', 'username', 'password') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'post_text', 'pub_date', 'user') Please help me spot the problem. Thanks in advance -
Django Rest Framework - create object with field value from URL
Is it possible to use a ModelViewSet to create an instance from a POST request where one of the field values is specified in the URL? EG: POST /teams/3/members with data name = Bob should create Member(team_id=3, name="Bob") Conceptually similar to filtering against the url -
pip install mysql-python fails with missing config-win.h
The python command is pip install mysql-python The full error is _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory Can someone please tell me how to fix this error? What exactly is mysql-python and how is it different from regular mysql? Another stack overflow post suggested installing it with a setup executable, where can I find this? I installed something called mysql python connector from here: https://downloads.mysql.com/archives/c-c/ It installed into C:\Program Files\MySQL\MySQL Connector C 6.1 However, I cannotfind mysqld executable anywhere in this folder -
Django 3.0.5 connection trouble to sql server 2012
I am trying to connect Django 3.0.5 to SQL server 2012 and I went through lots of posts on various websites. they mostly said that use "django-pyodbc-azure" but when I go to download that i found out it supports only django 2.1 so is there any other tool or something i am missing or i need to actually do my work only in django 2.1? -
Cannot navigate in django url smoothly
I am making a web app in django ,i have set the url path in "urls" file of the app and also set views but the problem is that when i click the menu items once it works , now when i am on that page when i click it some other button or even reclick the same menu option it gives an error , it seems like its not routing properly . i have to go back to home and then go to some other url... when first time i click menu item ( http://localhost:3000/chest/ ) route sets like this. when i click menu item in the new page it appends to the route like this ( http://localhost:3000/chest/bicep ) instead of this ( http://localhost:3000/bicep/ ). Code: urls.py from django.contrib import admin from django.urls import path from . import views # from django.conf.urls import url urlpatterns = [ path("", views.home, name = "HOME"), path("blog_detail/<int:id>", views.blog_detail, name = "blog"), # path("about/", views.about, name="about"), # path("contact/", views.contact, name="contact"), path("back/", views.back1, name="back"), # re_path(r'^back/$', views.back1, name="back"), path("chest/", views.chest, name="chest"), path("shoulder/",views.shoulder, name="shoulder"), path("abs/", views.abs, name="abs"), path("bicep/", views.bicep, name="bicep"), path("tricep/", views.tricep, name= "tricep"), path("forearm/", views.forearm, name="forearm"), path("legs/", views.legs, name="legs"), path("fullbody/", views.fullbody, name="fullbody"), path("search/", views.search, name="search"), … -
Matplotlib shift plot graph to left
I'm wondering if it is possible to shift the graph only to the left for the following plot graph. import matplotlib import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() fig.savefig("test.png") plt.show() I want to leave the x ticks the same but want to shift the graph so that the starting point of the graph is on y-axis. Any suggestions? Thank you in advance. -
Too many values to unpack in MultipleChoicefield choices, though the choices element is an iterable list
I have this form, with a multiplechoicefield. The choices, I need to first split the values I get from the queryset, and then have them seperated before I can use them. class SsReportOndemandForm(forms.Form): recipient_email = forms.MultipleChoiceField(required=False,choices=email_choices) I tried this, and I got a simple list. email_choices = [] for emails in SsReportType.objects.all().values_list('email', flat=True): email_choices.append(str(emails).split(",")) print(email_choices) I printed out the list email_choices and got smth like this [[u'sumassing@sa.com ', u'shidwvargh@ss.com ', u'seweatigund@ff.com'], [u'sumaswqeing@gg.com', u'sumasing@hh.com ', u'shivdargh@aa.com ', u'satqweigweund@gg.com']] Which is fine, but when I render the form, it shows me error : ValueError at /ssreport/on_demand_ssreport too many values to unpack Request Method: GET Request URL: http://127.0.0.1:8000/ssreport/on_demand_ssreport Django Version: 1.7.6 Exception Type: ValueError Exception Value: too many values to unpack Exception Location: /home/rohit/Documents/matrix_cloud/env/local/lib/python2.7/site-packages/django/forms/widgets.py in render_options, line 530 I cannot use tuple here , as I need to split the values. Any idea what I can do?? -
Django auth api
I am following this short tutorial to make an api to authenticate users with Django. The tutorial mentions that this should not be used in production and I wanted to know why as I plan to use it in production. Is it just the '*' in the allowed hosts part which shouldn't be used? https://afdezl.github.io/post/authentication-react-native-django-1/ thanks -
Contact Form with Django 3, G Suite - email sending error
Goal Deploying a landing page on Digital Ocean built with Django 3. Adding my G suite account to the contact form so people can type in their email, subject, message and send it to me. What I have done I have built my contact from with the following guide. I have tested it and it prints out all the parameters in the terminal as it should Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: helllo From: customeremail@gmail.com To: admin@example.com Date: Tue, 17 Mar 2020 14:29:40 -0000 Message-ID: <12121212121212.1222212121212.1212121212121212@mymachinename.local> This is the message. After I have finished the tutorial I have added/switched the following things to the settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'mayname@mycompanydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True I have purchased a G Suite subscription that contains G Suite SMTP relay service that can send 10'000 email/day. ERRORS 1.After the 1st run I have received the following e-mail: Sign-in attempt was blocked myname@businessemaildomainname.com Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access. Check … -
Importing csv file into django and getting list index out of range error
I'm trying to upload a csv file into my django projects and save data into my model. The problem is i'm getting list index out of range but the data is uploaded correctly and saved into model. Can anyone please help me to solve this issue? this is my method in views.py : def admin_upload(request): template = "admin_upload.html" prompt = { 'order': 'CSV fichier cef, cin, nom, prenom, group, module, note_1, note_2, note_EFM' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a CSV file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = Note.objects.update_or_create( cef=column[0], cin=column[1], nom=column[2], prenom=column[3], group=column[4], module=column[5], note_1=column[6], note_2=column[7], note_EFM=column[8] ) context = {} return render(request, template, context) my model : class Note(models.Model): cef = models.CharField(max_length=30, unique=True) cin = models.CharField(max_length=30) nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) group = models.CharField(max_length=10) module = models.CharField(max_length=30) note_1 = models.CharField(max_length=5) note_2 = models.CharField(max_length=5) note_EFM = models.CharField(max_length=5) When i upload a csv file the data get uploaded but i get list index out of range error: IndexError at /import/ list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/import/ Django Version: 3.0.2 Exception Type: IndexError … -
formset doesn't save data
I've got a problem and i don't know how to solve it. I created formset where you can write your question in poll. I used formset because in future i want to make dynamic form from it. For now i just wanted one form to see if it works and ... it doesn't. When i click button everything is working as expected but when i click on detail view i can't see my choices. Also there is no data from form in database. Here is my code: model.py class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE, null=False) 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 class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py class CreateChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ('choice_text',) def __init__(self, *args, **kwargs): self.question = kwargs.pop('question') super(CreateChoiceForm, self).__init__(*args, **kwargs) ChoiceFormSet = modelformset_factory(Choice, form=CreateChoiceForm, extra=1) class ChoiceFormSet(ChoiceFormSet): def __init__(self, *args ,**kwargs): self.question = kwargs.pop('question') super(ChoiceFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False def _construct_form(self, *args, **kwargs): kwargs['question'] = self.question return super(ChoiceFormSet,self)._construct_form(*args, **kwargs) views.py def createChoice(request, pk): question = get_object_or_404(Question, pk=pk) formset = forms.ChoiceFormSet(question=question) if request.method == 'POST': if formset.is_valid(): formset = forms.ChoiceFormSet(question=question, … -
Cannot assign "'type1'": "users.user_type" must be a "types" instance
I have a 'users' model that have a OneToOneField to UserModel and a ForeignKey Field to 'types' model. How can I save the ForeignKeyField in database? models.py: class types(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') name = models.CharField(max_length=100) def __str__(self): return self.name class users(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') user_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) mobile = models.CharField(max_length=20) def __str__(self): return self.mobile + "(" + self.user.first_name + " " + self.user.last_name + ")" @property def full_name(self): return '%s %s' % (self.user.first_name, self.user.last_name) @receiver(post_save, sender=User) def update_user_users(sender, instance, created, **kwargs): if created: users.objects.create(user=instance) instance.users.save() views.py: def signup(request): if request.method == 'POST': form = forms.SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.users.mobile = form.cleaned_data.get('mobile') user.users.user_type = form.cleaned_data.get('user_type') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('index') else: form = forms.SignUpForm() return render(request, 'user/signup.html', {'form': form}) forms.py: lass SignUpForm(UserCreationForm): mobile = forms.CharField(max_length=20) user_type = forms.CharField(max_length=100) class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'mobile', 'user_type', ) But, I have this error: Cannot assign "'type1'": "users.user_type" must be a "types" instance. -
how to change field type and retain choices defined in model django 3.0
I am new to Django, I am trying to change field type by retaining choices defined in model. this is my model class MyModel(models.Model): class Type(models.IntegerChoices): INDIRECT= 0 DIRECT = 1 BOTH = 2 name = models.CharField(max_length=20) category = models.IntegerField(choices=Type.choices) price= models.IntegerField() and this is my form class class MyForm(forms.ModelForm): #category = forms.ChoiceField(widget=forms.RadioSelect()) class Meta: model = SPA fields = [ 'name', 'category', 'price' ] I know we can change the field type with the above commented line. but it doesn't bring choices from model.... Please advice how to achieve it. -
django migration on kubernetes replica set
I ran in to a problem, while deploying the django application in kubernetes pod having 3 replicas. Here is the problem: -> I have some db migration to be run in the django application. -> The migration python manage.py migrate --noinput --fake-initial runs during the application startup. -> When I deploy my helm chart having this deployment with 3 replicas, all the 3 replica try to migrate at the same time, the db lock timeout happens. Or some migration fails, saying table already exist. This happens only during the the fresh helm install chart installation, as all pods comes up together. I have not faced this issue while helm upgrade due to rolling update strategy, because only 1 pods comes up and do the migration. My question is: -> Is their any way to tell the kubernetes to bring up replica one-by-one during the helm install just like it do during upgrade. -> Is their any way I can avoid my error through helm hooks, I cannot use helm preinstall (as I need service account and credential to connect to DB) or post install (As the worker thread in django app needs to be rebooted to make migration into effect) -
How can I store a list of model instances in a django model
I am trying to create a form generator in the django admin panel that allows users to create forms graphically by entering the form field name, field ID and field type. How can I go about doing this? I was thinking of creating a model for forms and referencing instances in the model of the whole form. Is this the best way to go about this? Is there a better way? Project is at librebadge.com -
Paginations with ajax and django
Here's the code for the views.py it's a method that receives the "get" request and then retreives the data of the objects after filtering in json format. my views.py @login_required(login_url='login') def filter(request, page=1): """Displays the results of the search for substitute products """ global data # First logic section value = request.GET.get('value') """ logic of seconde user search (get constum search with 3 fields ( grade, categorie, rating)) """ conditions = dict() for filter_key, form_key in (('grade', 'grade'), ('categorie', 'categorie'), ('rating__rating', 'rating')): value = request.GET.get(form_key, None) if value: conditions[filter_key] = value print(conditions) best_product = Product.objects.filter(**conditions) serialize_product = productSerializer(best_product, many=True) print(type(serialize_product.data)) context = { 'best_product': serialize_product.data, } print((context)) return JsonResponse(context) Here is the "query" code that retrieves the data entered (grade, category, rating) then sends it to the view(filter), after processing it retrieves the answer then displays all the objects (in "var html"). My problem is that I want to display just 15 objects at a time (pagination with 15 objects). my scripts.js $('#btn-filter').on('click', function (e) { e.preventDefault(); var grade = $('#grade').val(); var categorie = $('#categorie').val(); var rating = $('#rating').val(); $('#row-after').children().remove(); // alert( 'rating: ' + rating + ' grade: ' + grade+ ' categorie: ' + categorie ); $.ajax({ url: … -
Celery Eventlet Worker django.db.utils.DatabaseError within Docker
I have a web application which is locally run with docker-compose. It contains Django connected to PostgreSQL, Celery and RabbitMQ. Every time I run a shared_task I get the following DatabaseError. worker_1 | [2020-03-17 20:03:40,931: ERROR/MainProcess] Signal handler <bound method DjangoWorkerFixup.on_task_prerun of <celery.fixups.django.DjangoWorkerFixup object at 0x7fa4dbf3ead0>> raised: DatabaseError("DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140346062341232 and this is thread id 140345963084624.") worker_1 | Traceback (most recent call last): worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/utils/dispatch/signal.py", line 288, in send worker_1 | response = receiver(signal=self, sender=sender, **named) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 166, in on_task_prerun worker_1 | self.close_database() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 177, in close_database worker_1 | return self._close_database() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 186, in _close_database worker_1 | conn.close() worker_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner worker_1 | return func(*args, **kwargs) worker_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 286, in close worker_1 | self.validate_thread_sharing() worker_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 558, in validate_thread_sharing worker_1 | % (self.alias, self._thread_ident, _thread.get_ident()) worker_1 | django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140346062341232 …