Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Raw SQL Query using a list parameter fails
I have the following code: products = Product.objects.raw( 'SELECT DISTINCT ON(I.product_id) P.id, P.name, P.desc, C.name AS ram, I.image ' 'FROM products_product AS P ' 'LEFT JOIN categories AS RPC ON P.id = RPC.product_id ' 'LEFT JOIN company AS CP ON P.company_id = CP.id ' 'LEFT JOIN category AS C ON RPC.category_id = C.id ' 'LEFT JOIN image AS I ON I.product_id = P.id ' 'WHERE P.id IN %s', list ) I receive the following error: not all arguments converted during string formatting Instead of list I tried to use [2,4] or ['2', '4'] , same error. If I use without a parameter is working. I use PostgreSQL. -
Get correct results from the database in Django
I have three Django models as follows: class NewFeature(models.Model): application = models.CharField(max_length=50) name = models.CharField(max_length=250) start = models.DateTimeField(null=True, blank=True) stop = models.DateTimeField(null=True, blank=True) groups = models.ManyToManyField(to=Group) class NewFeatureDetails(models.Model): new_feature = models.ForeignKey(to=NewFeature) culture = models.CharField(max_length=3, blank=False, default='en') text = models.TextField() picture = models.ImageField(upload_to=settings.MEDIA_ROOT, blank=False, null=False) class NewFeatureRead(models.Model): new_feature = models.ForeignKey(to=NewFeature) user = models.ForeignKey(to=User) timeStamp = models.DateTimeField(auto_now=True) Thus start and stop in NewFeature model could be empty but they also could have values. I want all records from NewFeatureDetails model for which user_id doesn't exist in NewFeatureRead where: current_time is between start and stop from NewFeature if they exist or if only start exists I want only results where start < current_time and also if only stop exists I want only results where current_time < stop What I tried is something like this: def getNewFeatures(request): current_user_id = request.user.id new_features = NewFeatureDetails.objects.exclude(new_feature__newfeatureread__user_id=current_user_id) if new_features: features = [] for feature in new_features: start = feature.new_feature.start stop = feature.new_feature.stop current_time = datetime.datetime.now() // I'm stuck here return new_features Is there a better way? Can it somehow be done in the query? If not, how could I do it on this way, as I tried? -
Django: Queryset object filter, against another object's time range
I have 3 models, run, sensor_parameter and data. There are other ForeignKey relationships in between those, but run has no direct ForeignKey to either sensor_parameter or data. A run has a start_time and an end_time, and is related to a chamber. class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField(db_index=True) chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) A chamber has a relation to a sensor and a sensor has a set of sensor_parameter(s) class SensorParameter(models.Model): sensor = models.ForeignKey(Sensor) parameter = models.ForeignKey(Parameter) And a data point finally "belongs" to a sensor_parameter: class Data(models.Model): time = models.DateTimeField(db_index=True) sensor_parameter = models.ForeignKey(SensorParameter, on_delete=models.CASCADE) parameter_value = models.FloatField() I need to filter a list of sensor_parameter(s), that belong to a run, but my only link between them is a time value. Since data has a time stamp, and a run has start_time and end_time, I thought I could filter a list of data.sensor_parameter in a time period range. I'm not sure how to build that quieryset filter. I have imported datetime, and have access to django_filter. This is what I have so far in my views.py import datetime import django_filters def get(self, request): # Get a list of run objects, that are passed through the request run_ids = request.GET.getlist('id') runs … -
django-nvd3 TypeError: a.dispatch.render_start is not a function
i am using django 1.1.11 on ubuntu16 . Installed django-nvd3 as per documentation. While trying to use the demo linechart my web page doesn't show anything . in the browsers debug console this error is there TypeError: a.dispatch.render_start is not a function nv.d3.min.js:2:1299 Can anyone suggest what is going wrong ? -
How do i transfer images from Unity to Django server?
As it is, I want to transfer images from Unity to Django using 'UnityWebRequest.Post'. However, Request's dictionary(request.POST) in views.py was null. Can I get examples(source code), so that I can get the ultimate inspiration? -
Gunicorn Nginx chunked transfer encoding
I am developing a webpage with django and I want the user to upload code a docker on my server executes and the user gets the result back. It is working fine, however, I want live response now. Therefore, I send a stream. It works local with Django development server but not on my staging server with gunicorn and nginx. Django view: class ProgrammingExerciseTaskDetailView(TaskDetailView): model = ProgrammingExercise template_name = 'desk/tasks/programming_exercise_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['programmingexercise'] = context['task'].programmingexercise return context def post(self, request, task_slug): if request.is_ajax() is False or request.method != "POST": return HttpResponse('only POST.', status=500) programming_exercise = get_object_or_404(ProgrammingExercise, slug=task_slug) solution = request.POST.get('solution') # manage_docker_container starts a docker and returns the stdout out_buffer = manage_docker_container(programming_exercise.language, solution) if UserSuccess.objects.filter(user=request.user, taskbase=programming_exercise).first() is None: UserSuccess.objects.create( user=request.user, taskbase=programming_exercise, successful=True) return HttpResponse(out_buffer, task_slug, status=200) Gunicorn: gunicorn --log-level debug --timeout 180 --access-logfile - --workers 3 --bind XXX Nginx: server { ... chunked_transfer_encoding on; location / { include proxy_params; proxy_buffering off; proxy_read_timeout 180; fastcgi_read_timeout 180; proxy_http_version 1.1; proxy_pass XXX.sock; } } JS: xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(msg){ $("#output").append(msg.currentTarget.response); console.log(msg.loaded+"bytes"); }, false); return xhr; }, Example 1: That's the code the user posts import time i = 0 while i <= 20: … -
Creating a pre-authenticated session in a django test
this is my first ever post as I have found hundreds of answers before by searching. So, thank you and please bear with me. I am working through the excellent book Test Driven Development with Python and trying to apply it to my project. There is test code for skipping the login process by pre-authenciating a session: from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, SESSION_KEY, get_user_model from django.contrib.sessions.backends.db import SessionStore from .base import FunctionalTest User = get_user_model() class MyListsTest(FunctionalTest): def create_pre_authenticated_session(self, email): user = User.objects.create(email=email) session = SessionStore() session[SESSION_KEY] = user.pk session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0] session.save() ## to set a cookie we need to first visit the domain. ## 404 pages load the quickest! self.browser.get(self.live_server_url + "/404_no_such_url/") self.browser.add_cookie(dict( name=settings.SESSION_COOKIE_NAME, value=session.session_key, path='/', )) This is called in a test like: def test_logged_in_users_can_do_something(self): email = 'edith@example.com' self.browser.get(self.live_server_url) self.wait_to_be_logged_out(email) # Edith is a logged-in user self.create_pre_authenticated_session(email) print(self.browser.get_cookies()) self.browser.get(self.live_server_url) print(self.browser.get_cookies()) self.wait_to_be_logged_in(email) # code to test that this user can do something... self.browser = selenium.webdriver.Firefox() is defined in the FunctionalTest base class setUp(). This works fine for the User model used in the book which is derived from models.Model. The problem is that when I customise the user model further and inherit from AbstractUser or … -
Should I avoid using models in django migrations?
I am working on an existing Django project that contains migration code like: someFluffyModel.objects.all().delete() or someModel = SomeModel(....) someModel.save() Now wherever there is such code and newer migrations change the schema that reflect the current version of the model, there is an issue in applying migrations from scratch. As I understand the reason is that the model used in the migration doesn't reflect the model used in the migration at that point in time. As I have found fixtures can help in loading data but how about deletion? Is the preferred way to manually delete data from the database? -
Multi line plot Bokeh + django
I am facing problem to draw multi-line plot using django and bokeh. here is my view.py def bokeh(request): if request.method == "GET" : measuringIdString = '1098' experimentIdString = '7884,7886' measuringIdArray = measuringIdString.split(',') experimentIdArray = experimentIdString.split(',') xyMeasurement={} i=0 for measuringId in measuringIdArray: for experimentId in experimentIdArray: allData = MeasurementsExperiments.objects.all().filter(measuring_setup_id=measuringId) & MeasurementsExperiments.objects.all().filter(experiment_id=experimentId) xMeasureTime=[] yMeasureValue=[] for data in allData: xMeasureTime.append(data.measurement_time.time()) yMeasureValue.append(data.measured_value) xyMeasurement[i]=MeasurementXY(xMeasureTime,yMeasureValue) i+=1 print "i=0: TIME= ",xyMeasurement[0].time, ", value = ",xyMeasurement[0].value print "i=1: TIME= ",xyMeasurement[1].time, ", value = ",xyMeasurement[1].value #print yMeasureValue plot = figure(title= title , x_axis_label= 'Time', x_axis_type='datetime', y_axis_label= 'Measured Value', plot_width =600, plot_height =400) #plot.line(xyMeasurement[1].time, xyMeasurement[1].value, legend= 'f(x)', line_width = 2) plot.multi_line(xs=[xyMeasurement[0].time,xyMeasurement[0].value], ys=[xyMeasurement[0].time,xyMeasurement[0].value], color=['red','green']) #Store components script, div = components(plot) return render_to_response( 'projects/load_graph.html', {'script' : script , 'div' : div} ) else: pass class MeasurementXY: def __init__(self, time, value): self.time = time self.value = value #print "time :", self.time #print "value :",self.value def displayValues(self): print "Time : ", self.time, ", Value: ", self.value The value I am receiving are i=0: TIME= [datetime.time(13, 4, 7), datetime.time(13, 23, 24), datetime.time(14, 11, 49)] , value = [Decimal('0.020000000000'), Decimal('0.010000000000'), Decimal('0.080000000000')] i=1: TIME= [datetime.time(13, 4, 7), datetime.time(13, 23, 24), datetime.time(14, 11, 49)] , value = [Decimal('-0.010000000000'), Decimal('0E-12'), Decimal('0.030000000000')] But the graph looks like My Questions are: … -
Django 1.11 SAML2 Authentication
I am trying to do sso from okta to my django 1.11 web application hosted on Apache webserver 2.4.I am using django-saml2-auth and used the plugin https://github.com/fangli/django-saml2-auth I am using python 3.5 and RHEL 7.4 My settings.py is as below SAML2_AUTH = { # Required setting 'METADATA_AUTO_CONF_URL': 'https://example.okta.com/app/exkw7v22qt6qP7BcN2p678ttt/sso/saml/metadata', # Optional settings below 'DEFAULT_NEXT_URL': '/admin', # Custom target redirect URL after the user get logged in. Default to /admin if not set. This setting will be overwritten if you have parameter ?next= specificed in the login URL. 'NEW_USER_PROFILE': { 'USER_GROUPS': [], # The default group name when a new user logs in 'ACTIVE_STATUS': True, # The default active status for new users 'STAFF_STATUS': True, # The staff status for new users 'SUPERUSER_STATUS': False, # The superuser status for new users }, 'ATTRIBUTES_MAP': { # Change Email/UserName/FirstName/LastName to corresponding SAML2 userprofile attributes. 'email': 'Email', 'username': 'UserName', 'first_name': 'FirstName', 'last_name': 'LastName', }, #'TRIGGER': { # 'CREATE_USER': 'path.to.your.new.user.hook.method', # 'BEFORE_LOGIN': 'path.to.your.login.hook.method', #}, 'ASSERTION_URL': 'http://example.com', # Custom URL to validate incoming SAML requests against 'ENTITY_ID': 'http://example.com/ssoapp/authenticate/', # Populates the Issuer element in authn request 'NAME_ID_FORMAT': None, # Sets the Format property of authn NameIDPolicy element When the request comes to my server , I am … -
Celery task method is not getting called
I have the following method call & particular method in a Python Django web application. (Please note that I am not that much familiar with python, Django or celery) Method as follows : @shared_task(bind=True, default_retry_delay=10, max_retries=3, ignore_results=False) def push_sns_message(self, sns_alias, message, target_arn): """ Celery task """ logger.debug("########## Hit the Celery Task ###############") print "########## Hit the celery ###########" connection = sns_connections[sns_alias] return connection.publish(message=message, target_arn=target_arn) Method Call as follows: print "########## Calling to celery ###########" push_sns_message.s(self.sns_connection, json.dumps(wrapper[0]), self.sns_arn) The issue is whenever I run application, it comes to push_sns_message.s() but doesn't go inside it. I can see the print "########## Calling to celery ###########" but cannot see following print and also other lines also are not called "########## Hit the celery ###########" Please explain this behavior. -
I am fatch data by username from django API using angular4
this is my anglar4 creating app name as search i want to fatch data from django rest API. I want that when i give username it give me only this username data. app.components.tc import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { username:string = ''; constructor(private httpClient:HttpClient){} onNameKeyUP(event:any){ this.username = event.target.value; } getProfile(){ console.log(this.username) this.httpClient.get("http://127.0.0.1:8000/loginAdmin/?username=${this.username}") .subscribe( (data:any[]) => { console.log(data); } ) } } app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } app.components.html it is my simlple Html which is use to send username from Django API <input type="text" (keyup)="onNameKeyUP($event)"> <button (click)="getProfile()">Get Profile</button> -
Django & ajax : control the 'data' returned by Ajax query
I have two fields depending on a field. until now I can make one field dependent but not both because i dont know how to control data variable of Ajax. $("#id_type1").change(function () { var url = $("#personForm").attr("data-tiers-url"); // get the url of the `load_cities` view var typeID = $(this).val(); // get the selected country ID from the HTML input // alert(countryId) $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'tiers': typeID // add the country id to the GET parameters }, success: function (data) { // `data` is the return of the `load_cities` view function alert(data) $("#id_tiers").html(data); // replace the contents of the city input with the data that came from the server } }); }); this is the views that returns data it contains tree variables : def load_tiers(request): tiers_id = request.GET.get('tiers') print(tiers_id) tiers = operation_Bancaire.objects.all().filter(type_tiers=tiers_id) #print(cities) frs="Fournisseur"; clt="1"; if tiers_id=="Fournisseur": frs = operation_Bancaire.objects.all().filter(type_tiers=tiers_id) elif tiers_id=="client": clt = operation_Bancaire.objects.all().filter(type_tiers=tiers_id) return render(request, 'appOne/city_dropdown_list_options.html', json.dumps({'tiers': tiers,'frs':frs,'clt':clt})) I need to control this data : $("#id_tiers").html(data); to give #id_tiers just the value of data['frs'] and not 'tiers','frs','clt' can you please help me to achieve this because i'm new to Ajax, and js … -
How to make ajax call from django template
I'm trying to make ajax call from django template. In y urls I have an url as follows: url(r'^update_new_feature_read/$', update_new_feature_read, name="update_new_feature_read"), The view update_new_feature_read is as follows: def update_new_feature_read(request): print("test") return "test" And the ajax call inside django template is as follows: features_popup.on('click', "#next-arrow", function (e) { e.preventDefault(); var feature_id = parseInt($('[data-slide-id="'+ current_slide_id +'"]').attr('id')); $.ajax({ type: "POST", url: '{% url "update_new_feature_read" %}', data: { feature_id: feature_id, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function (result) { debugger; }, error: function (data) { console.log(data); console.log("Error"); debugger; } }); }); But I'm getting an error: Reverse for '"update_new_feature_read"' with arguments '()' and keyword arguments '{}' not found. I'm using very old Django version. It's 1.4, but it's out of the question to update it. -
Sortable function of jQuery(using django and bootstrap)
I am trying sortable tag list using jQuery, but not react it. what is the cause of the problem? Currently, list display without jquery is done normally. django 2.0 bootstrap 4.0 base.html <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> {% block domready %} {% endblock %} list.html <div class="card-body"> {% for tag in tags %} <ul class = "list-group order"> <li class = "list-group-item"><a href="{% url 'app:tag' tag.name %}">{{ tag.name }}</a></li> </ul> {% endfor %} </div> {% block domready %} <script> $(function() { $( '.order' ).sortable(); }); </script> {% endblock %} -
i cannot fetch the json data from http://127.0.0.1:8000 my django localhost server in android
private void jsonParse() { String url = "http://127.0.0.1:8000/products/products/?format=json"; JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { public void onResponse(JSONArray response) { try { // `response` is the JSONArray that you need to iterate for (int i = 0; i < response.length(); i++) { JSONObject o = response.getJSONObject(i); int id = o.getInt("id"); String title = o.getString("title"); String description = o.getString("description"); String price = o.getString("price"); mTextViewResult.append(title + ", " + String.valueOf(id) + ", "+price +"," + description + "\n\n"); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); mQueue.add(request); } } This is my android code. There is no error in it because i can fetch the json from https://api.myjson.com/bins/z7hbb (Which is in online). But Whenever i fetch it from my django localserver http://127.0.0.1:8000/products/products/?format=json (This is my rest api link ) it cannot fetch the json data. My this link http://127.0.0.1:8000/products/products/?format=json is also ok because it's also show the json data [{"id":1,"title":"t-shirt","description":"this is a good t-shirt","price":"39.99"},{"id":2,"title":"Jeans","description":"this is a jean","price":"89.99"}] I'm stuck here.Don't get any error or clue to solve this. -
Django app with other apps as dependencies
Imagine you create a reusable django app 'A' which depends on another reusable django app 'B'. Now if I want to use an app 'A' I have to add not only 'A' but also 'B' in INSTALLED_APPS? How do I add only 'A' without explicitly adding 'B' too? -
How to Insert using M2M relationship, and intermediary table, and through_fields?
I have this model from this question: class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Tag(models.Model): tag = models.CharField(max_length=50) def __str__(self): return self.tag class Video(models.Model): title = models.CharField(max_length=255) categories = models.ManyToManyField(Category, through='Taxonomy', through_fields=('video', 'category')) tags = models.ManyToManyField(Tag, through='Taxonomy', through_fields=('video', 'tag')) def __str__(self): return self.title class Taxonomy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) Then I used the python manage.py shell: # Added the models from app1.models import Category, Tag, Video, Taxonomy # Added some categories c1 = Category(category="c1") c2 = Category(category="c2") c3 = Category(category="c3") c4 = Category(category="c4") c5 = Category(category="c5") c1.save() c2.save() c3.save() c4.save() c5.save() # Added some tags t1 = Tag(tag="t1") t2 = Tag(tag="t2") t3 = Tag(tag="t3") t4 = Tag(tag="t4") t5 = Tag(tag="t5") t1.save() t2.save() t3.save() t4.save() t5.save() # Created a video instance v1 = Video(title = "title1") v1.save() # This is when I tried to add a category using get_or_create() v1.categories.get_or_create(category="c1") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Program Files\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py", line 994, in get_or_create self.add(obj) File "C:\Program Files\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py", line 893, in add (opts.app_label, opts.object_name) AttributeError: Cannot use add() on a ManyToManyField which specifies an intermediary model. Use app1.Taxonomy's Manager instead. I got stuck here, … -
django call a view with optional argument
I wrote a middleware that prevents from users in certain group to access a view, If a user without permission tries to access the page it should redirect him to a login with a message (saying he has no permissions). I thought to do it like that: have a login view: def login_view(request, permission=None): and in the middleware: class ManagerRequiredMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'user') if not request.user.groups.filter(name='Manager').exists(): path = request.path_info.lstrip('/') if not any(m.match(path) for m in EXEMPT_URLS) and not any(m.match(path) for m in MANAGER_URLS): print('no manager') next = request.path_info #return redirect('/login/?next=%s' % next, permission=True) #return HttpResponseRedirect(reverse('login', kwargs={'permission': True})) return redirect('/login/?next=%s' % next) as you can see I tried multiple things. I want to keep the where he tried to access (to redirect him after login), but also want to call login_view with the permission flag on so I can display the right message. I don't want this argument to be visible in the URL. Thanks. -
Django CBV ListView, accessing both paginated and unpaginated results
I built a list view using generic view class ListView with pagination and search functionality. Now I want to include in the same page a map with markers for all the results, without pagination. Is there a way to reach both paginated and unpaginated results without having to do a duplicate query? -
django model ForeignKey relation
I have 3 models User, lesson and company class User(models.Model): pass class lesson(models.Model): user = models.Foreignkey(User) company = models.Foreignkey(Company) class Company(models.Model): pass How can I add one lesson for two companies -
Django Parler how to access translated model field from a mixin
I have written this model class Course(TranslatableModel): translations = TranslatedFields( title = models.CharField(max_length=200), overview = models.TextField(), slug = models.SlugField(max_length=200, unique=True)) owner = models.ForeignKey(User, related_name='courses_created') subject = models.ForeignKey(Subject, related_name='courses') created = models.DateTimeField(auto_now_add=True) order = OrderField(blank=True, for_fields=['title']) class Meta: ordering = ('order',) def __unicode__(self): return self.title AND ALSO THIS mixin class class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin): fields = ['subject', 'title', 'slug', 'overview'] success_url = reverse_lazy('manage_course_list') template_name = 'courses/manage/course/form.html' The "fields = ['subject', 'title', 'slug', 'overview']" line is causing the error Exception Type: FieldError Exception Value: Unknown field(s) (overview, slug, title) specified for Course How to I refer to the translated fields ?? If i remove 'title', 'slug', 'overview' from the fields list it works.. -
Django query- 'not equal to' filter
I am writing a Django query to filter a list of teams which the user is a part of. (The Team and UserTeams models i am querying): class Team(models.Model) name = models.CharField(max_length=100) venue = models.CharField(max_length=100) countryID = models.ForeignKey(Countries, on_delete=models.CASCADE) owner = models.ForeignKey(User) class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) The first query (teamquery) filters the Teams by checking if the owner=request.user, and I then print a list of these teams in my template. Below that I then want to print a list of teams where the UserTeams UserID = request.user,(userteamquery) but the problem I have is that some teams are appearing in both query results, so are printed in both lists. Is there a 'not equal' query i can use where it will exclude all UserTeams in the userteamquery where the teamID is a result of teamquery? so teamID=teamquery @login_required def teamsview(request): teamquery = Team.objects.filter(owner=request.user) userteamquery = UserTeams.objects.filter(userID=request.user) return render(request, 'teammanager/teams.html', { "teams": teamquery, "userteams": userteamquery}) -
Django views.py CreateView
I'm currently doing my second Django project and I want to know something about views.py in my first project I had classes that had the field: model = 'name model' or form_class = 'name form' some of them had both and now in my second project I have class that has: form_class = forms.UserCreateForm How should I know which one should I use - from forms or from models and why this time Django won't let me do: form_class = UserCreateForm and needs this 'forms.' -
Celery task .get() not working
I will really appreciate help with this! This is my first attempt at using Celery with Django in Docker containers and I can't get passed this problem after many hours of reading and experimenting. PROBLEM I can import the task from polls.task and run it using .delay() as follows: python manage.py shell from polls.tasks import add task = add.delay(4,4) When I run this, I can see a message through the rabbitmq container. If I execute task.id, i can get the task id. HOWEVER, if I run task.get(), the program just hangs. I see no action on any of the containers and I get no result. I have also noticed that, when I run dc-up and start all the containers, I get the following output on the worker container, which seems correct: worker | -------------- default@5d0902ad9e2a v4.1.0 (latentcall) worker | ---- **** ----- worker | --- * *** * -- Linux-4.9.87-linuxkit-aufs-x86_64-with-debian-8.10 2018-03-30 09:45:01 worker | -- * - **** --- worker | - ** ---------- [config] worker | - ** ---------- .> app: composeexample:0x7f2f3255e320 worker | - ** ---------- .> transport: amqp://admin:**@rabbitmq:5672// worker | - ** ---------- .> results: redis://redis:6379/0 worker | - *** --- * --- .> concurrency: 2 (prefork) …