Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django build is taking so much time in jenkins?
I am using jenkins for continuous integration from gitlab and continuous deployment. My "execute shell" consist of the following commands . #!/bin/bash source /my_env/bin/activate # Activate the virtualenv cd /var/lib/jenkins/workspace/Operations_central #pip install -r requirements.txt # Install or upgrade dependencies python manage.py makemigrations python manage.py migrate # Apply South's database sudo service nginx restart fuser -n tcp -k 8088 gunicorn applicationfile.wsgi:application --bind=myserverip:portno` -
not able to run manage.py runserver
Below is the problem i am facing while running the server. I'm not able to start manage.py runserver . I'm Using sqlite3 database. I am trying to run quite basic application. system configurations: windows 10, python 2.7 Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation. All rights reserved. C:\Users\rutwi_000>cd C:\Python27\Scripts\mysite C:\Python27\Scripts\mysite>C:/Python27/python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 16, in <module> from django.db.migrations.executor import MigrationExecutor File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 7, in <module> from .loader import MigrationLoader File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 10, in <module> from django.db.migrations.recorder import MigrationRecorder File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 12, in <module> class MigrationRecorder(object): File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 26, in MigrationRecorder class Migration(models.Model): File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 27, in Migration app = models.CharField(max_length=255) File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__ self._setup(name) File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File … -
How can I change a Django db to MySQL on pythonanywhere?
I thought this would be simple because of this MySQL tutorial by pythonanywhere, but I'm still having trouble switching over from sqlite3. I'm a beginner to SQL databases, and I've been checking out other stackoverflow questions but I'm not sure where else to go from here. Here's what I've done so far. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '3DPrince$ubodb', 'USER': '3DPrince', 'PASSWORD': 'secretpassword', 'HOST': '3DPrince.mysql.pythonanywhere-services.com', }, } I've also run the following to try and sync the db. manage.py makemigrations manage.py migrate I'm still getting the error that (1146, "Table '3DPrince$ubodb.django_site' doesn't exist") I'm not sure what else to do from here and I'm not sure how to do any sort of checks from the mysql bash console. Can anyone point out what I'm doing wrong? Or maybe some useful mysql bash commands to check the connection or manually remake the db? -
Django: Only run once when multiple objects created or on `save` when only one object is changing
I have two models in a Django application, one being a collection of the other: class Document(models.Model): title = models.CharField(max_length=128) ... syllables = models.PositiveIntegerField() ... def set_statistics(self): """Computationally heavy task to set or update all document statistics including `syllables`""" ... class Section(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE) text = models.TextField() For every section, there is a computationally intensive function to calculate the syllables (among other statistics) for the aggregated text from each section. I would like to run this set_statistics() function for the document as few times as possible. Ideally, things work work like this: class Section(models.Model): ... # This doesn't seem to actually work when adding objects with an admin inline def bulk_create(self, *args, **kwargs): super(Section, self).bulk_create(*args, **kwargs) self.document.set_statistics() ... def save(self, *args, **kwargs): super(Section, self).save(*args, **kwargs) self.document.set_statistics() # This runs once for every section, I want # it to only run once if there are multiple # sections being added at the same time Any thoughts? -
How to create Django sophisticated pdf template?
I need to create in Django sophisticated pdf documents that will be populated with some variable fields. I am already generating simple pdfs reportlab.pdfgen import canvas but customer requires pdfs where pdf is assembled from several text blocks and not simple row based. Is there easy way to do it? -
Filter output by model property
In my model I have calculated property current_tobe_payed I want to generate csv report of all rows where my property current_tobe_payed is less then zero See my view below: def export_leaseterm_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="leaseterm.csv"' writer = csv.writer(response) leaseterms = serializers.serialize( "python", LeaseTerm.objects.all()) [obj for obj in leaseterms if obj.current_tobe_payed > 0] for leaseterm in obj: writer.writerow(leaseterm['fields'].values()) return response However I am getting error: 'dict' object has no attribute 'current_tobe_payed' how can I solve this issue? (also I want to enter into csv only certain fields and not all the table.) -
django.template.exceptions.TemplateDoesNotExist:
I have a python program that uses django and it generates the error django.template.exceptions.TemplateDoesNotExist. I made a sample of code to illustrate my problem. I created two files a test_file.py and HelloTemplate.txt, located in the same directory C:\Games\Game1. #file name: test_file.py from django.template.loader import get_template from django.conf import settings settings.configure(DEBUG=True,TEMPLATE_DIRS=('.', )) #I also tried TEMPLATE_DIRS=('C:\Games\Game1', ), didn't solve the problem import sys def main(): myTemplate = get_template("HelloTemplate.txt") if __name__ == '__main__': main() The second file is a txt file with a line Hello as fellow: filename: HelloTemplate.txt Hello Template Here's the error that I got Traceback (most recent call last): File "test_file.py", line 17, in <module> main() File "test_file.py", line 13, in main myTemplate = get_template("HelloTemplate.txt") File "C:\WinPython-32bit-2.7.5.3\python-2.7.5\lib\site-packages\django\template\loader.py", line 25, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: HelloTemplate.txt Thanks for your help to fix this error. -
why does venv reference different python version
I followed djangogirls tutorial to get started with django and had everything working. Once I finished the basic tutorial, everything in working order, I decided to go through the steps again to make something new and become more familiar with using git, django, venv, etc. fyi - I am on windows 10 and have python 2.7 and python 3.5 installed. I am using python 3.5.2 with django 1.10.4. steps: >mkdir v2 >cd v2 >"d:/python 3.5.2/python" -m venv myenv >cd myenv/scripts/activate (myenv) python -m pip install -U pip for some reason this is the only way I was able to upgrade pip this time around (myenv) d:/v2/myenv/scripts> pip install django~=1.10.0 (myenv) d:/v2/myenv/scripts> django-admin.py startproject mysite This is where the magic doesn't happen: d:\v2>django-admin.py startproject mysite2 Traceback (most recent call last): File "D:\v3\myenv\Scripts\django-admin.py", line 2, in <module> from django.core import management File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 10, in <module> from django.apps import apps File "C:\Python27\lib\site-packages\django\apps\__init__.py", line 1, in <module> from .config import AppConfig File "C:\Python27\lib\site-packages\django\apps\config.py", line 4, in <module> from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured File "C:\Python27\lib\site-packages\django\core\exceptions.py", line 5, in <module> from django.utils.encoding import force_text File "C:\Python27\lib\site-packages\django\utils\encoding.py", line 11, in <module> from django.utils.six.moves.urllib.parse import quote, unquote File "C:\Python27\lib\site-packages\django\utils\six.py", line 92, in __get__ result = self._resolve() … -
Lifetime and scope of class and instance variables in django
While there are quite a few questions and answers on here already about the life of different variables within python I am looking for how they translate into the django environment in terms of application scope and endpoint scopes. Here is a simple version of what I am making and I want to ensure that it will behave the way I am expecting it to my_cache/models/GlobalCache.py: # This class should be global to the entire application and only # load when the server is started. class GlobalCacheobject): _cache = {} @classmethod def fetch(cls): return cls._cache @classmethod def flush(cls): cls._cache = {} @classmethod def load_cache(cls, files_to_load_data_from): for file in files_to_load_from: cls._cache[file] = <load file and process its data into an entry> my_cache/models/InstanceCache.py: from .GlobalCache import GlobalCache # This class will contain a reference to the global cache and use it to look # up entries. class InstanceCache(object): def __init__(self, name=None): self._name = name self._cache = GlobalCache.fetch() def fetch_file_data(self, file_name): cache_entry = self._cache.get(file_name, None) if cache_entry is None: raise EntryNotFoundException() return ReadOnlyInterfaceObject(cache_entry) The intent is to have GlobalCache have a cls._cache value that will persist as long as the server is running. Calling GlobalCache.flush() will drop its global reference to the data … -
Testing Django querysets: self.assertListEqual vs self.assertQuerysetEqual
Testing in Django I've found two different ways to test functions that involve querysets. The first one is: test_instance = FooFactory() self.assertListEqual(list(Foo.objects.all()), [test_instance]) And the second one is: test_instance = FooFactory() self.assertQuerysetEqual(Foo.objects.all(), map(repr, [test_instance])) Which of these two are better? I read from the Django docs that this is what assertQuerysetEqual does: Asserts that a queryset qs returns a particular list of values values. The comparison of the contents of qs and values is performed using the function transform; by default, this means that the repr() of each value is compared. Any other callable can be used if repr() doesn’t provide a unique or helpful comparison. By default, the comparison is also ordering dependent. If qs doesn’t provide an implicit ordering, you can set the ordered parameter to False, which turns the comparison into a collections.Counter comparison. If the order is undefined (if the given qs isn’t ordered and the comparison is against more than one ordered values), a ValueError is raised. I see two important things here: one is that the repr() of each value is compared, and the other is that assertQuerysetEqual allows you to make ordering optional. For the first point, I think it's better to compare … -
Django Custom Model Field - formfield not working
I've been scratching my head for a while now over this one. I'm trying to build a custom model field to store postal address. The general idea is to store all data after serializing in a models.TextField, and to use a form.MultiValueField to catch each value. For some reason, even if migration works fine, in the admin, the field appear as a simple TextField. As if the MultiValueField part was completely ignored... Here's my code: from django.db import models from django.forms import MultiValueField, CharField from django.utils.translation import ugettext_lazy as _ class Address(object): """A postal address.""" def __init__(self, street, postal_code, city, country, complement=None, region=None): self.street = street self.complement = complement self.postal_code = postal_code self.city = city self.region = region self.country = country def print_address_inline(self): complement = '' region = '' if self.complement: complement = ', %s' % self.complement if self.region: region = ', %s' % self.region data = { 'street': self.street, 'complement': complement, 'code': self.postal_code, 'city': self.city, 'region': region, 'country': self.country } return '%(street)s%(complement)s, %(code)s %(city)s%(region)s' \ ', %(country)s' % data def __str__(self): return self.print_address_inline() class AddressFormField(MultiValueField): def __init__(self, *args, **kwargs): del kwargs['max_length'] error_messages = { 'incomplete': _('Enter a complete address: ' \ 'street, postal code, city and country.'), } fields … -
Django model unique=True for migrations only
Consider a User model with a field username = Charfield(unique=True). When a duplicate is submitted, Django Rest Framework returns the error user with this username already exists. I haven't been able to find the code that does this, only that the error message is contained in various django.po files as msgid "%(model_name)s with this %(field_labels)s already exists." (I have no usage of internationalization). This would imply that Django is doing some "magic", i.e. making a trip to the database to check for existence. I would like for Django to not do this. Uniqueness should be enforced only at the database via migrations. How can this be done, without resorting to manual edits of the database or migrations file? -
Django - How to get the value of a decimal field of object
I looked through the QuerySet API reference and couldn't find anything that allowed me to get the actual value, as a decimal, of a field of a specific object. Everything I've tried doesn't return it as the actual decimal value. For example, Hours.objects.filter(fullname=fullname).values(hours) doesn't return the number of hours as a decimal value. I'm trying to get the number of hours of a user, mathematically add a number to it (e.g. 15.5 + 4.25) and save it back (as 19.75). -
Celery does not send all tasks in the queue
In a Django application I try to send mails asynchronously using Celery, the tasks objects are created, but they do not reach Celery. Here I show the id of the tasks created: 0: d51a86c2-219d-44a5-a004-2ff00f13f229 1: 47979e10-643c-4ced-808a-bdefb2a1779f 2: e52b0a58-3742-4547-9f37-0fe5b065a8ae But in my Celery shell. python manage.py celery worker -l info -Ofair --settings=project.settings.staging Only some tasks are executed: [2016-12-19 17:15:17,582: INFO/MainProcess] Received task: apps.enrollment.tasks.send_email_professor[d51a86c2-219d-44a5-a004-2ff00f13f229] [2016-12-19 17:15:17,586: WARNING/Worker-5] 0 [2016-12-19 17:15:17,610: INFO/MainProcess] Received task: apps.enrollment.tasks.send_email_purchase[e52b0a58-3742-4547-9f37-0fe5b065a8ae] [2016-12-19 17:15:17,616: WARNING/Worker-6] 2 [2016-12-19 17:15:17,992: WARNING/Worker-6] email sent [2016-12-19 17:15:18,152: WARNING/Worker-5] email sent Sometimes only the 1, sometimes 0 and 2, and sometimes 1 and 2. The print I do at the beginning of each task. My configuration of Celery and Redis is: BROKER_URL = 'redis://localhost:6379/0' BROKER_TRANSPORT = 'redis' BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 800000,} CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYD_POOL_RESTARTS = True CELERYD_CONCURRENCY = 8 CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' REDIS_NOTIFICATION_HOST = 'localhost' REDIS_NOTIFICATION_PORT = 6379 REDIS_NOTIFICATION_DB = 5 -
Error binding parameter 0 - probably unsupported type with CheckboxSelectMultiple
I'm using the django form wizard and getting this error when I use any multiple selection. I don't know why I'm getting it but I think it's because I'm passing multiple datas because it does work with a unique selection (like radioselect). Error binding parameter 0 - probably unsupported type Here is the code : forms.py class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe('<div><p class="companyname" style="%s">My company</p></div>' % (obj.font_css)) class ContactForm1(forms.ModelForm): choice_box = CustomChoiceField(widget=forms.CheckboxSelectMultiple, queryset=ImageCheckView.objects.all(), empty_label=None) class Meta: model = ImageCheckView fields = ['title', 'choice_box'] def __init__(self, *args, **kwargs): super(ContactForm1, self).__init__(*args, **kwargs) self.fields['choice_box'].empty_label = None views.py class ContactWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def get_context_data(self, form, **kwargs): context = super(ContactWizard, self).get_context_data(form=form, **kwargs) if self.steps.current == '0': context.update({'datas': ImageCheckView.objects.all()}) return context def done(self, form_list, **kwargs): form_data = process_form_data(form_list) context = {'form_data': form_data} return render_to_response('done.html', context) def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] return form_data Any suggestion to resolve this issue ? -
How Django complex query will be return (Django Aggregation)?
I am looking for an answer to this but couldn't find the exact answer. I am practicing Django and want to understand the working of the query. -
Access nfs mount from Django Apache app
My Django app, running from Apache mod_wsgi, is trying to access some files that are on a Mounted NFS drive on CentOS. The python code inside the django app has a few os.path lines such as os.path.isdir('/nfs/mountednfs') That return errors when run from the django app (confirmed these are infact mounted). Turning off SELinux and rebooting did not resolve this -
Service in submodule of AngularJS app unavailable
I am using webpack 1.13.3 and AngularJS 1.5.8. I am restricted to Angular 1 and would love to use webpack since it seems to bundle nicely. I am using Django REST Framework for my API, however, this is irrelevant in large part. I set up a project with authentication and created some users using angular-django-registration-auth. https://github.com/Tivix/angular-django-registration-auth I followed this tutorial and created a basic project structure. I made the webpack entry point angularDjangoRegistrationAuthApp and yay, everything worked, API and all as well as Token Authentication after tweaking CSRF token, however when I try and make my entry point myApp and tried to load the index.html, the JS console showed some errors: Error: [$injector:nomod] Module 'angularDjangoRegistrationAuthApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. http://errors.angularjs.org/1.5.8/$injector/nomod?p0=angularDjangoRegistrationAuthApp Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. http://errors.angularjs.org/1.5.8/$injector/nomod?p0=myAp Here is my index.html: {% load staticfiles %} <html> <head> <title>Project</title> <script type="text/javascript" src="{% static … -
Annotating related and multi-filtered objects in Django
I have a queryset of profiles: Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True) ... View: Profile.objects.select_related('user') Each user/profile can register for multiple events per day: Models: class Event(models.Model): title = models.CharField(max_length=120) date = models.DateField(default=default_event_date) ... class Registration(models.Model): event = models.ForeignKey(Event) student = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) block = models.ForeignKey(Block, on_delete=models.CASCADE) .... Given a Date how can I annotate (?I think that's what I want?) one Registration object per block (filtered on the user/profile and the Event__Date) In the end, what I'm trying to output in my template is something like this: For Date: 19 Dec 2016 User/Profile Block A Block B ... user1 None None user2 Event1 Event2 user3 Event3 None ... -
How do I place django rest nested serializer's fields to serializer?
In the following code, template is a foreign key. template is nested serializer to question serializer. [{ "pk": 15, "template": { "question_type": 1, "question": "What is your age ?", "answer_type": 1, "available_choices": [] }, "order": 1, "mandatory": true }] What I want to show is: [ { "pk": 15, "question_type": 1, "question": "What is your age?", "order": 1, "answer_type": 1, "mandatory": true, "available_choices": [] }] How do I show nested serializers data fields like this ? This is my serializer class: class TemplateSerializer(serializers.ModelSerializer): available_choices = ChoiceSerializer(many=True) class Meta: model = Template fields = ( 'question_type', 'question', 'answer_type', 'available_choices' ) class ASerializer(serializers.ModelSerializer): template = TemplateSerializer() class Meta: model = A fields = ( 'pk', 'template', 'order', 'mandatory' ) -
Heroku push failed with weird error message
I've had a Django app running on Heroku for a while now. Couldn't find this error online when it came up: $ git push heroku master ... remote: -----> Uninstalling stale dependencies ... remote: $ pip install -r requirements.txt remote: remote: $ python manage.py collectstatic --noinput remote: 66 static files copied to '/tmp/build_2271dc3bd9820ee9e10847bbab5f6b47/xxx/staticfiles', 66 post-processed. remote: remote: mv: inter-device move failed: ‘/app/.heroku/src’ to ‘/tmp/build_2271dc3bd9820ee9e10847bbab5f6b47/.heroku/src’; unable to remove target: Is a directory remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to xxx. remote: To https://git.heroku.com/....git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/xxx.git' $ I tried running git push heroku +master also and that didn't work either. Any ideas? -
How can i write a Regex for url of my api?
url http://localhost:port/api/text/arabic stemmer algorithm i have created one but it take just the first word : r'text/(?P<text>\w+)/?' i'm using Django framework -
Take old chat message from database (channels + Django + Redis)
Hello i have chat which work perfect, save old messages to datebase. But i can't render this old messages when reload the chat page. Have next code. in chat/models.py import json from django.db import models from django.utils.six import python_2_unicode_compatible from channels import Group from orders.models import Order from .settings import MSG_TYPE_MESSAGE @python_2_unicode_compatible class Room(models.Model): """ A room for people to chat in. """ order = models.OneToOneField(Order, on_delete=models.CASCADE) # Room title title = models.CharField(max_length=255) # If only "staff" users are allowed (is_staff on django's User) is_closed = models.BooleanField(default=False) def __str__(self): return self.title @property def websocket_group(self): """ Returns the Channels Group that sockets should subscribe to to get sent messages as they are generated. """ return Group("room-%s" % self.id) def send_message(self, message, user, msg_type=MSG_TYPE_MESSAGE): """ Called to send a message to the room on behalf of a user. """ final_msg = {'room': str(self.id), 'message': message, 'username': user.username, 'msg_type': msg_type} # write to database room = Room.objects.get(pk=self.id) if message: message = Message.objects.create(room=room, message=message) message.save() # Send out the message to everyone in the room self.websocket_group.send( {"text": json.dumps(final_msg)} ) class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) message = models.TextField(null=True, blank=True) in chat/index.html have javascipt which render chat in realtime. <script> $(function () { // Correctly … -
Django: Checking if object exists in queryset
THE PROBLEM: The issue I am having is getting the price of the option within the Selection model. This is because, depending on which other Options are also within the same cart, different prices will be used to generate the total. I need help with a queryset that gets me the price of the Option, if the option has an effector_option that itself is within the same cart, used that, otherwise use the Variation with only the option field set. TempName App model consists of: class Section(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=100) temp = models.ForeignKey(TempName, null=False) def __str__(self): return self.title def get_options(self): return self.option_set.all() class Option(models.Model): name = models.CharField(max_length=120) section = models.ForeignKey(Section, null=False) def __str__(self): return self.name def get_variations(self): return self.variation_set.all() class Variation(models.Model): name = models.CharField(max_length=60, blank=True, unique=True) price = models.DecimalField(max_digits=5, decimal_places=2) option = models.ForeignKey(Option, null=False) effector_option = models.ForeignKey(Option, null=True, blank=True, related_name='option_effected') def __str__(self): return self.name There can be many Sections on one page. Each Section can contain many Options which will later be selectable by the user. The selected Option will go in the cart which will be used to generate the total price. Within Variation model, the field option simply tells me which option the Variation belongs … -
Run celery with django on AWS Elastic Beanstalk using environment variables
I want to run celery on AWS Elastic Beanstalk with my Django app. I followed this great answer of @yellowcap (How do you run a worker with AWS Elastic Beanstalk?). So my supervisord.conf looks like this : files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A myappname --loglevel=INFO directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv" # Create the celery supervisord conf script echo "$celeryconf" | tee /opt/python/etc/celery.conf # Add configuration script to supervisord conf (if not there already) if ! grep …