Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modifying Google Calendar API to accept environment variables rather than a JSON file for Heroku
I'm pushing a Django site (python 2.7) to Heroku, however I'm getting the error: raise InvalidClientSecretsError('File not found: "%s"' % filename) oauth2client.clientsecrets.InvalidClientSecretsError: File not found: "calendar_secret.json" When running a cron job, and that's because my file calendar_secret.json isn't in my repo. I purposefully didn't push it so that the data isn't known for security reasons. My question is about how to modify Google's default code found here: https://developers.google.com/google-apps/calendar/quickstart/python, specifically the get_credentials method in order to use environment variables in either JSON or in the method directly so that I don't have to upload my calendar secrets. Here's Google's code: def get_credentials(self): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'json-file.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials Which works great. But … -
How to get image from the web and save it to a imageField using the url
I'm trying to get a image from the web and save it to the imageField using the images url. The below code spits out a error ('JpegImageFile' object has no attribute '_committed'). from PIL import Image import urllib.request import io if form.is_valid(): instance = form.save(commit=False) URL = 'http://www.image.jpg' with urllib.request.urlopen(URL) as url: file = io.BytesIO(url.read()) img = Image.open(file) instance.image = img -
display data in mongodb database using django 1.8 and mongodb
I am using mongoengine with Django 1.8 and my project needs to connect to one instances of MongoDB while another with sql.so first i decided to do all work related to mongodb database. i want to display 'battery_status' column or document in my table 'location' which is in mongodb database 'pom'. but it is not displaying any data . plz help me out... url.py- url(r'^managebusiness/list/$',login_required(Travel_Details.as_view()),name='Travel_Details'), url(r'^datatable/lists/$',views_cluster.Travel_Details.OrderListJson.as_view(), name = 'order_list_json'), setting.py import mongoengine BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DBNAME = 'pom' _MONGODB_USER = 'admin' _MONGODB_PASSWD = 'root' _MONGODB_HOST = 'localhost' _MONGODB_NAME = 'pom' _MONGODB_DATABASE_HOST = \ 'mongodb://%s:%s@%s/%s' \ %(_MONGODB_USER,_MONGODB_PASSWD,_MONGODB_HOST,_MONGODB_NAME) mongoengine.connect(DBNAME,host=_MONGODB_DATABASE_HOST) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'admin_db', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', }, } model.py class location(Document): user_id = IntField(blank=True, null=True) name = StringField(max_length=100) loc_lon = FloatField(blank=True, null=True) timestamp = DateTimeField(blank=True, null=True) activity = StringField() lot_lat = FloatField(blank=True, null=True) batter_status = StringField() address = StringField() date_created = DateTimeField(auto_now_add=True) view.py import hashlib import json import sys import datetime from django.core.cache import cache from django.views.generic import View from django.shortcuts import render from django_datatables_view.base_datatable_view import BaseDatatableView from django.http import HttpResponse, HttpResponseNotFound from django.shortcuts import get_object_or_404, render ,render_to_response from django.template import Context, RequestContext from django.utils import timezone from django.utils.crypto import get_random_string from django.template.loader import … -
Why can't I connect to my localhost django dev server?
I'm creating a django app and in the process of setting up my local test environment. I can successfully get manage.py runserver working but pointing my browser to any variation of http://127.0.0.1:8000/, http://0.0.0.0:8000/, or http://localhost:8000/ returns a "This site can’t be reached" error. Simultaneously, django will throw a 301 error: Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [11/Jul/2017 23:35:37] "GET / HTTP/1.1" 301 0 I've successfully deployed the app to Heroku (all URLs work there), but I can't get it running on my local machine. I've also tried heroku local's included dev server to the same effect. For reference my django urls.py file looks like: from django.conf.urls import url from django.contrib import admin from clothing_recommendation.views import RequestEmailAnalysis, CheckEmailAnalysisStatus, index urlpatterns = [ url(r'^$', index, name='index'), url(r'^admin/', admin.site.urls), url(r'^analyze_email/', RequestEmailAnalysis), url(r'^analyze_email/status/', CheckEmailAnalysisStatus), ] Any help appreciated! -
Django: HTTP error 410 (Gone) with RedirectView
I get an HTTP 410 error when invoking the following Django View: >>> views.py: class ReopenMilestoneView( dj_auth_mixins.LoginRequiredMixin, dj_views.RedirectView ): pattern_name = 'milestone_dashboard' def dispatch(self, request, *args, **kwargs): print('DISPATCH BEGIN') instance = project_models.Milestone.objects.get(pk=kwargs['pk']) instance.state = project_models.STATE_OPEN instance.save() print('DISPATCH END') return super(ReopenMilestoneView, self).dispatch( request, *args, **kwargs ) >>> urls.py: ... url( r'^milestone/dashboard/$', project_views.MilestoneDashboard.as_view(), name='milestone_dashboard' ), url( r'^milestone/(?P<pk>[\w-]+)/dashboard/$', project_views.MilestoneDashboard.as_view(), name='milestone_specific_dashboard' ), ... The dispatch method is invoked ("DISPATCH" appears on the console); however, Django "runserver" is returning the following error code: DISPATCH BEGIN DISPATCH END Gone: /doc/milestone/2/reopen/ [12/Jul/2017 07:03:30] "GET /doc/milestone/2/reopen/ HTTP/1.1" 410 0 I have used "RedirectView" before but I have never got this error, any ideas? Django is not returning a lot of info back... -
Django Rest Framework - Nested Serialization with intermediary model
I have three models, one of them being an intermediary model linking the other two. I can properly nest these two models via foreign key relation, but I would like to use this intermediary model to link them together since having direct key relation is undesirable in the situation. Desired output at the bottom. models.py class Parent(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class Child(models.Model): given_name = models.CharField(max_length=128) # reverse relation works, but an intermediary model is preferred # parent = models.ForeignKey(Parent, related_name="parents" on_delete=models.PROTECT) class Link(models.Model): parent = models.ForeignKey(Parent, on_delete=models.PROTECT) child = models.ForeignKey(Child, on_delete=models.PROTECT) serializers.py class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = '__all__' class LinkSerializer(serializers.ModelSerializer): # what should I place here? class Meta: model = Link fields = '__all__' class ParentSerializer(serializers.ModelSerializer): children = LinkSerializer(many=True) class Meta: model = Parent fields = ('id', 'first_name', 'last_name', 'children') api_output.json { "id": 1, "first_name": "John", "last_name": "Appleseed", "children": [ { "id": 1, "given_name": "Uno Appleseed" }, { "id": 2, "given_name": "Dos Appleseed" } ] } -
Show additional data when checkbox is true Django
I'm working at my first project in Django and learning it by the way. Currently I'm stuck at the part of the project where I have to show additional data if checkbox is selected as true. For example if checkbox is selected it have to show select list of data. Is there easy way how to accomplis this? Thanks for help. -
ImportError: cannot import name 'update_contenttypes'
When I try to execute command ‘source toaster start’, it aborts an error. Before that, I just source a virtual environment, and really thanks for the help. Traceback: Traceback (most recent call last): File "/home/pajamas/Documents/GitRepo/repo4/5/ostro-os/bitbake/bin/../lib/toaster/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/pajamas/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/pajamas/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/home/pajamas/.local/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pajamas/.local/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/pajamas/.local/lib/python3.5/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/pajamas/.local/lib/python3.5/site-packages/django/contrib/contenttypes/apps.py", line 7, in <module> from .management import update_contenttypes ImportError: cannot import name 'update_contenttypes' -
Django Haystack: Search_indexes how to filter on a custom field
I am using Django Haystack for elasticsearch. I have a model whereby I need to filter the data on a custom field. class KeyStoreIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) custom = indexes.BooleanField() def prepare_custom(self, obj): return True def get_model(self): return KeyStore def index_queryset(self, using=None): return self.get_model().objects.filter(custom=True) How can I achieve the same? I need to filter on custom Using that field as part of index_queryset gives below error. django.core.exceptions.FieldError: Cannot resolve keyword 'isOwner' into field. Choices are: ........... -
Django / Let's Encrypt / Apache2: Permission denied: '/var/www/.private'
I'm setting up a new Django project using Let's Encrypt ands Apache2 (which I've done several times before) and I suddenly getting the follow error when I try and enter the site. [Wed Jul 12 06:46:20.282234 2017] [mpm_prefork:notice] [pid 11872] AH00163: Apache/2.4.18 (Ubuntu) OpenSSL/1.0.2g mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal oper$ [Wed Jul 12 06:46:20.282277 2017] [core:notice] [pid 11872] AH00094: Command line: '/usr/sbin/apache2' [Wed Jul 12 05:46:25.380046 2017] [wsgi:error] [pid 30828] Cryptokey not found in /var/www/.private/django_secure.key, creating random key [Wed Jul 12 05:46:25.380222 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] mod_wsgi (pid=30828): Target WSGI script '/var/www/stella/stella/wsgi.py' cannot be loaded$ [Wed Jul 12 05:46:25.380234 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] mod_wsgi (pid=30828): Exception occurred processing WSGI script '/var/www/stella/stella/ws$ [Wed Jul 12 05:46:25.380259 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] Traceback (most recent call last): [Wed Jul 12 05:46:25.380278 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] File "/var/www/stella/stella/wsgi.py", line 16, in <module> [Wed Jul 12 05:46:25.380333 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] application = get_wsgi_application() [Wed Jul 12 05:46:25.380345 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] File "/var/www/stella/env/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in $ [Wed Jul 12 05:46:25.380388 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] django.setup(set_prefix=False) [Wed Jul 12 05:46:25.380399 2017] [wsgi:error] [pid 30828] [remote 31.53.130.64:17067] File "/var/www/stella/env/lib/python2.7/site-packages/django/__init__.py", line … -
How to Push data from Web service into my database
I got one web service http://52.74.43.70/PMKVYData/PMKVYInformation.asmx/Details. How can I push extracted data into my Database. -
django access m2m field attribute from a queryset
I am trying to show one of attribute of a M2M field in django template from a queryset. Reservation(models.Model): hotel = models.ForeignField(Hotel) rooms = models.ManyToManyField(Room, through='ReservationRoom') Room(models.Model): number = models.IntegerField(default=0) Now from Reservation queryset, i am trying to access rooms fiels attribute i.e number in django template(using jinja template)like this, % for res in reservations %} <tr> <td>{{ loop.index }}</td> {% for room in reservations.rooms_set.all%} <td>{{ room.number }}</td> {% endfor %} </tr> and the views def arrivals(request, hotel): res = Reservation.objects.filter(hotel=hotel) return render(request, "sample.html", {'reservations': res}) But throwing following error, 'django.db.models.query.QuerySet object' has no attribute 'rooms_set' what i have done wrong? -
How to pass user input to os command line interface using Python
I need one help. I am passing some user input to views.py file and need to pass those input param to os command line interface using python. I am explaining my code below. rname = request.POST.get('react') if 'strt' in request.POST: status = 1 if 'shutbt' in request.POST: status = 0 if 'susbtn' in request.POST: status = 2 passw = Reactor( rname=rname, status=status, ) passw.save() Here I am getting the user input by post method and before save into database I need to pass both param i.e-status and rname to os command line interface . Please help. -
Heroku local invalid port number or address:port pair - deploying django app
I have this ProcFile file following this guidelines for django app deployment: web: python manage.py runserver 0.0.0.0:$PORT Then running heroku local or heroku local web got me into this error: CommandError: "0.0.0.0:$PORT" is not a valid port number or address:port pair. -
Django template internationalization - non-Roman (Greek)
I'm having an issue with Django, and title-casing non-Roman strings in templates. From what I've read, there can be similar issues around apostrophes, but in this case, it's accented characters. Currently, the basics of my code looks like this: {% extends 'layout.html' %} {% load static %} {% load i18n %} {% block content %} {% language 'el' %} {% for sub_dir in sub_dirs %} {{sub_dir.name |title}} {% endfor %} {% endlanguage %} {% endblock %} The source in the variable is: μουσικές και σκοποί του πόντου The result I get is: ΜουσικέΣ Και Σκοποί Του ΠόΝτου The result that I want, is: Μουσικές Και Σκοποί Του Πόντου The English that's intermixed, presents fine. In this case, I know that there's only one other potential language involved, so I tried specifying it, which isn't making a difference. I also wonder what happens in the case of multiple non-Roman/Latin scripts, but one issue at a time. For the language code, according to various charts, I've tried 'el', 'el-gr', 'el-GR', and 'gr' Any help would be appreciated. Thanks -
(Python, Django)Which choose i tech between websocket(django channels) and mqtt(paho) for remote control to change device's picture or video?
first of all, I'm sorry that my english skill is not good. I shoud make an IoT project that Clients access web site(Using Django) to remote control his electronic display to change picture or video. but I don't know what is the best choice to make chat server that can transfer files and notify current playback information. -
Default celery countdown
Is there a way to declare a default countdown timer in django's settings.py like CELERYD_TASK_SOFT_TIME_LIMIT? It will be helpful if there is rather than just always declaring it in my class-based periodic task like? try: ddd except Exception as exc: raise self.retry(exc=exc) Also is it possible to have like default set of retry=True to all tasks? -
Django: ValueError at /search/ A string literal cannot contain NUL (0x00) characters
My production server was being scanned by a hacker and I got a few of these Django alert emails notifying me of this error below. What should I do to prevent this? ValueError at /search/ A string literal cannot contain NUL (0x00) characters. views.py: def profile_search(request): query = artist = title = None if request.method == 'GET': artist = request.GET.get("artist") title = request.GET.get("title") if artist is not None and artist != '': artist1 = Q(artist__name__icontains=artist) query = artist1 if title is not None and title != '': title1 = Q(title__icontains=title) if query: query = query & title1 else: query = title1 context = { "artist": artist, "title": title, "query": query, } return render(request, "profile_search.html", context) traceback: Exception Type: ValueError at /search/ Exception Value: A string literal cannot contain NUL (0x00) characters. Request information: USER: AnonymousUser GET: artist = ‘../../../../etc/passwd\x00’ POST: No POST data FILES: No FILES data -
websocket not connecting (django-channels)
I literally cloned this repo: https://github.com/jacobian/channels-example and it doesn't work. I was at first just getting "disconnect"s, then I changed the secret key to something static (tutorial used random generator for secret key) and not I'm getting both "handshake" and "disconnect" Django version: 1.10 python version: 2.7 channels version: 1.1.6 Traceback: System check identified no issues (0 silenced). July 11, 2017 - 23:02:30 Django version 1.10, using settings 'chat.settings' Starting Channels development server at http://127.0.0.1:8000/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the server with CTRL-BREAK. 2017-07-11 23:02:30,127 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-11 23:02:30,131 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-11 23:02:30,132 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-11 23:02:30,141 - INFO - worker - Listening on channels http.request, websocket .connect, websocket.disconnect, websocket.receive 2017-07-11 23:02:30,147 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2017-07-11 23:02:30,161 - INFO - server - Using busy-loop synchronous mode on channel l ayer 2017-07-11 23:02:30,167 - INFO - server - Listening on endpoint tcp:port=8000:interface =127.0.0.1 [2017/07/11 23:02:40] WebSocket HANDSHAKING /chat/wild-bird-7042/ [127.0.0.1:53847] [2017/07/11 23:02:41] HTTP GET /wild-bird-7042/ … -
Add comments to article django createview foreignkey
I would like to add comments to my article using django createview. At the moment, I can add articles without a problem. I can add comments. But I can't add the comments to the correct articles. I have been at this for two days. I would really like to do this with cbv, as I am trying to learn. Any help in explaining what I am doing wrong and how to correct it would be much appreciated. models.py class Article(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, null=True, blank=True) content = models.TextField(default='') author = models.ForeignKey(User) featured_image = models.ImageField(upload_to='articles/featured_image', default='') created = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(blank=True, null=True) update_author = models.ForeignKey(User, null=True, blank=True, related_name="+") class Meta: verbose_name = 'Article' verbose_name_plural = 'Articles' ordering = ['-created',] def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Article, self).save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:article-detail', kwargs={'slug': self.slug}) class ArticleComment(models.Model): article = models.ForeignKey(Article, related_name='comments', null=True) author = models.ForeignKey(User, null=True) text = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Article Comment' verbose_name_plural = 'Article Comments' def __str__(self): return self.text views.py class ArticleDetailView(DetailView): model = Article context_object_name = 'article' def get_context_data(self, **kwargs): context = super(ArticleDetailView, self).get_context_data(**kwargs) article = Article.objects.all() context['sidebar_articles'] = article.order_by('-created')[:15] return context … -
Django - Single Form for List of Multiple Object Instances
I'm making a Django application that stores a list of athletes and displays them on a page. I have a form to create athletes but what I want to do is make a form that I can use to edit them in a pop-up window on the same page they are listed. I know I could create one form for each instance and display each form when the corresponding edit button is clicked, but that seems really inefficient. Is there any way to create one form and then essentially pass it the ID of an athlete when the edit button for that athletes is clicked? -
Extend Django Sites, Site model
[Django 1.11 Python 3.5 PostgreSQL 9.5] I make model and relate it with Site through OneToOneField. class SiteExtend(models.Model): class Meta: verbose_name = 'Стили и Метрики' verbose_name_plural = 'Стили и Метрики' site = models.OneToOneField(Site, related_name='extending', verbose_name='Сайт', on_delete=models.CASCADE) style = models.TextField('CSS', null=True, blank=True) script = models.TextField('JavaScript', null=True, blank=True) active = models.BooleanField('Активен', default=False) playable = models.BooleanField('Играбельный', default=True, help_text='Будет ли на этом сайте происходить розыгрышь?') def __str__(self): return self.site.__str__() And unregister and register Site model and my model with admin.StackedInline class SiteExtensionsInline(admin.StackedInline): model = models.SiteExtend can_delete = False class SiteAdmin(BaseSiteAdmin): inlines = (SiteExtensionsInline,) admin.site.unregister(Site) admin.site.register(Site, SiteAdmin) When I try add new Site fill only Site inputs(not inline my model) all ok and all save, and if later open to edit this Site and fill inputs my model all ok, but if I try right away fill inputs my inline model I get error: Exception Type: IntegrityError at / admin / sites / site / add / Exception Value: ERROR: the repeated value of the key violates the uniqueness constraint "main_siteextend_site_id_key" DETAIL: The key "(site_id) = (20)" already exists. Maybe someone came acrossed this? -
How to create object with Foreign Key
Fisrt,here is my models: class Question(models.Model): description = models.CharField(max_length=200) analysis = models.CharField(max_length=50) def __str__(self): return self.description class QuestionOption(models.Model): question = models.ForeignKey(Question,related_name='options') content = models.CharField(max_length=100) isAnswer = models.BooleanField() def __str__(self): return self.question.description + " " + self.content My Serializers: class QuestionSerializer(ModelSerializer): class Meta: model = Question fields = '__all__' The Serializer of QuestionOption is as same My ViewSet: class QuestionViewSet(ModelViewSet): queryset = Question.objects.all() serializer_class = QuestionRetriveSerilzer I want to post a Json data,like this: { "options": [ { "content": "This is the first option", "isAnswer": false }, { "content": "This is the second option", "isAnswer": true } ], "description": "which one is true?", "analysis": "It's esay" } I hope my QuestionViewSet can create a Question and two QuestionOption for me automatically,and when I post that Json data,the options is null list,so I override the create method of QuestionViewSet,like this: def create(self, request, *args, **kwargs): serializer = QuestionSerializer(data=request.data) question = serializer.save() for data in request.data['options']: data['question'] = question.id optionSeializer = OptionSerializer(data=data) print optionSeializer.is_valid() optionSeializer.save() return Response(serializer.data,status=status.HTTP_200_OK) And this method can work,but I want to find a simpler way to do it,cause I must override update and other methods,it's not a easy task... So how to design Serializers and ViewSet in order to … -
Cannot get Visual Studio 2015 to hit Django project debug point
I've created a django web project and I'm doing my best to try to debug it. The problem is that I want to be able to put a debug point inside a function for the django rest framework, but no matter where the debug point is put it will not hit. I'm using Visual Studio 2015 with Python Tools for Visual Studio 2.2.0 installed. I am having this problem whether or not I use the launch with debugging or attaching via the tcp interface (using the ptvsd module). The peculiar thing is that if I am debugging over tcp, it will break upon trying to load registry keys in one of the django files (as not all of them are mime types) even though they are encapsulated in a try..except block. This happens regardless if it is the project that I am currently working in, or a brand new django web project produced by Visual Studio. I am able to hit the debug points placed in manage.py, however I'd like to debug the actual django application when running. Realistically I'd like to hit a debug point in one of the django rest framework serializer model functions (get_...) in order to … -
Running Django app in docker-compose: connection to postgres db refuses the first time but works afterwards
I have this weird problem that can be reproduced with the simple tutorial from Docker. If I follow the tutorial exactly, everything would work fine, i.e. after docker-compose up command, the web container would run and connect nicely to the db container. However, if I choose to create the same Django project on the host, change its settings for the postgres db, and copy it over to the web image in its Dockerfile, instead of mounting the host directory to the container and doing those things there as shown in the tutorial (using the command docker-compose run web django-admin.py startproject composeexample . and then change the settings file generated and located in the mounted directory on the host), the first time I run docker-compose up, the web container would have problems connecting to the db, with the error as below web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (172.18.0.2) and accepting web_1 | TCP/IP connections on port 5432? However, if I stop the compose with docker-compose down and then run it again with docker-compose up, the web container would connect to the db successfully with no problems. 'Connection refused' …