Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested serializers
I'm new to Python/Django/DRF. I'm not sure how to deal with the following case: I have the 3 models: Article, Image, ImageEntryItem as below, how can I make ArticleSerializer to use a ImageSerializer ? class Article(models.Model): headline = models.CharField(_('headline'), max_length=255, db_index=True) body = models.TextField(blank=True, null=True) class ImageEntryItem(models.Model): image = models.ForeignKey(Image) entry = models.ForeignKey(Article, related_name='imageentryitems') order = models.IntegerField(null=True, blank=True) class Image(models.Model): exif = models.TextField(null=True, blank=True) def get_image_url(self): # return image url This is my current Article Serializer: class ArticleSerializer(serializers.ModelSerializer): first_image = serializers.SerializerMethodField() class Meta: model = Article fields=('headline', 'body', 'first_image') def get_first_image(self, article): first_image = article.imageentryitems.all()[0].image image_url = first_image.get_image_url() exif = first_image.exif return { image_url: image_url, exif: exif } Can I do something to use a ImageSerializer like http://www.django-rest-framework.org/api-guide/relations/#nested-relationships? I'm not sure how to do it here because Aritcle is not directly related to Image, how can I use ImageSerialzier on article.imageentryitems.all()[0].image ? class ArticleSerializer(serializers.ModelSerializer): first_image = ImageSerializer(read_only=True) -
Docker Compose and Django generator syntax error
I'm new to Docker and have been trying to set up Django with Docker. I've been following the instructions here but am running into the error down below. File "/usr/local/lib/python3.7/site- packages/django/contrib/admin/widgets.py", line 152 web_1 | '%s=%s' % (k, v) for k, v in params.items(), web_1 | ^ web_1 | SyntaxError: Generator expression must be parenthesized My Django version is 2.1, Python 3.7. As far as I know, this shouldn't be happening, yet it is. I have checked the file in question, and it is written correctly. It was a fix that was put into place that should have fixed this error in the past with the latest version of Python. From widgets.py: if params: related_url += '?' + '&'.join('%s=%s' % (k, v) for k, v in params.items()) This is the entire definition: def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) rel_to = self.rel.model if rel_to in self.admin_site._registry: # The related object is registered with the same AdminSite related_url = reverse( 'admin:%s_%s_changelist' % ( rel_to._meta.app_label, rel_to._meta.model_name, ), current_app=self.admin_site.name, ) params = self.url_parameters() if params: related_url += '?' + '&'.join('%s=%s' % (k, v) for k, v in params.items()) context['related_url'] = mark_safe(related_url) context['link_title'] = _('Lookup') # The JavaScript code looks for … -
How to except database transaction submit for a model in Django?
Example I have two models: class Customer: ... class ImportResult: ... What happen is I would like to import Customer from file to our database and update the ImportResult progress. Here the sample code: with transaction.atomic(): Customer.objects.create(**data) import_result.update_progress() import_result.save() The problem is that because import_result also inside transaction I cannot get the progress at the time it updated. The data only submit to database when transaction completed. Noted that when update_progress() called we used Pusher to update the web in realtime. So the question is are there anyway to excepting or force import_result to commit to database right away? -
Serving Multiple RASA bots on Django Backend
I’m currently trying to serve multiple bots (running different models) and to allow users to interact with it on a website. I’ve had a look at the following: http://www.rasa.com/docs/nlu/http/, http://www.rasa.com/docs/core/http/ and http://www.rasa.com/docs/nlu/python/, but I’m still having trouble figuring out how it can be done. Some of the solutions I’ve considered are either: Serve the bot on a HTTP server and have my website interact with the Rasa HTTP server Create the website on Django Framework or REST API, and run Rasa Core and NLU on the backend. What would be the best way to go about doing this? And, could anyone please briefly explain how this can be done (with multiple bot models and instances running)? Any help would be greatly appreciated! -
Django 2.0 Notifications: How to overwrite the default list.html page for django-notifications
So, I recently imported Django-notifications and have successfully added a notification or two. Now I want to look at the list page. In my urls I have added the notification endpoint path('notifications/', include("notifications.urls")), and when I go to the url, I get the output that matches the documentation: Now, How do I go about changing the notification url. I tried to create an app for notifications python manage.py startapp notifications, but it said that one already existed. I feel like I'm missing something simple, but I can't put a finger on it. -
Django - Forms - change field names on template
I have to following forms.py and models.py: # models class BHA_Component(models.Model): item_description = models.CharField(max_length=111) num_of_jts = models.CharField(max_length=111) length = models.CharField(max_length=111) cum_length = models.CharField(max_length=111) outer_d = models.CharField(max_length=111) # forms class BHA_Component_Form(forms.ModelForm): class Meta(): model = BHA_Component fields = '__all__' So far, I've been printing the field names on the screen using html like this: {% for field in bha_form %} <label>{{ field.name }}</label> {% endfor %} I passed in the form, bha_form as a context variable in views.py. If I use this set of code, it this on a screen: item_description, num_of_jts, length, cum_length, outer_d But I want to print this on a screen: Item Description, # of jts, Lenth, Cum. Len., OD As you can see, I can't get this output by simply using some s.upper() method, or regex method, because there no certain string transformation relationship between the original field names and the output I want. I want to manually decide what field names will be printed on a screen for each field. But I don't want to do this by hard coding html elements like this: <label>Item Description</label> <label># of jts</label> <label>Length</label> I want to do this on the backend using Django. How should I go about this? -
Starting a python project with Admin and REST API
I'm starting a new project with Python3 and Django, i have only 2 business rules to this project: Receive Car Plates by a REST API in a HTTP POST endpoint After receive this Car Plate i should put more informations like: price and date entrance and exit and give a manage Admin Site to my end user So, i'm newbie in Python and i have some doubts about how to organize my project, let's see: important: this is my project on github https://github.com/rlanhellas/safepark 1) I have a carplate folder that contains models and views, so i use it for my admin site. But i need receive this information from a REST Endpoint, so i created another project called "safepark-api" with only one file called carplate.py that have all endpoints HTTP. This is the better way to do it Or i should put everything in carplate folder (generated by django) ? I'm thinking that putting Endpoints together with carplate folder (generated by django) i'm breaking the MVC Architecture, because controllers and logic should be separated from "view". 2) When putting code on github is normal push the virtual environment too ? 3) Looking for my github project and understanding that safepark-api … -
django error __str__ returned non-string (type __proxy__)
I have some models that use GenericForeignKey, and when I try to access them with Django Admin util, I can see the list of records, but when I click on one of them, I get this error: __str__ returned non-string (type __proxy__). This is the code of one of the models: class ReservationComponent(models.Model): reservation = models.ForeignKey(Reservation, on_delete=models.PROTECT, related_name='components', verbose_name=_('')) day = models.DateField(verbose_name=_('Day')) content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: verbose_name = _("Reservation Component") verbose_name_plural = _("Reservations Components") def __str__(self): return "[{}][{}]{} - [{}]{}".format(self.id, self.reservation, self.day, self.content_type, self.object_id) -
Running scrapy on django project in views
I am trying to run a scrapy script in one of my views behind the scenes to get some information for me and have tried many different ways like using crawl, crawlprocess, scrapyd etc. and all of them return errors. The scrapy script runs perfectly from its own file but when I try to run it from views I get many errors. Any suggestions are appreciated. (Trying to add it to def at the bottom of the views file). import scrapy from scrapy import Spider from scrapy import Request from scrapy.crawler import CrawlerProcess class ProductSpider(scrapy.Spider): product = input("What product are you looking for? Keywords help for specific products: ") name = "Product_spider" allowed_domains=['www.amazon.ca'] start_urls = ['https://www.amazon.ca/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords='+product] #so that websites will not block access to the spider download_delay = 30 def parse(self, response): crawler = self.crawler_process.create_crawler() # xpath is similar to an address that is used to find certain elements in HTML code,this info is then extracted product_title = response.xpath('//*/div/div/div/div[2]/div[1]/div[1]/a/@title').extract() product_price = response.xpath('//span[contains(@class,"s-price")]/text()').extract() product_url = response.xpath('//*/div/div/div/div[2]/div[1]/div[1]/a/@href').extract() # yield goes through everything once, saves its spot, does not save info but sends it to the pipeline to get processed if need be yield{'product_title': product_title, 'product_price': product_price, 'url': product_url,} #it is checking the … -
how to retrieve data in ManyToMany relationship field in Django Admin according to the selected data of foreign key field
How to retrieve all question in ManyToMany field according to the selected exam_name(foreign key) in Django Admin? -
Wagtail: Updating Django 1.10.8 -> 1.11 - ImportError: cannot import name 'FieldPanel'
I'm currently working on upgrade my Wagtail sites and got stuck. Wagtail: 1.13.4 Django: 1.10.8 Site works fine in Django 1.10.8 but throws an ImportError: cannot import name 'FieldPanel' in 1.11 when i attempt to python manage.py runserver. I don't have any migrations to do, and i've checked as i've stepped my Wagtail versions up from 1.5 through this point. I have a custom user model, in an app called members and they're declared in my project settings like so: INSTALLED_APPS = [ 'home', 'search', 'overextends', 'dashboard', 'lineage', 'gunicorn', 'wagtail.wagtailforms', 'wagtail.wagtailredirects', 'wagtail.wagtailembeds', 'wagtail.wagtailsites', 'wagtail.wagtailusers', 'wagtail.wagtailsnippets', 'wagtail.wagtaildocs', 'wagtail.wagtailimages', 'wagtail.wagtailsearch', 'wagtail.wagtailadmin', 'wagtail.wagtailcore', 'wagtail.contrib.modeladmin', 'members', 'modelcluster', 'compressor', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] #lots of extra stuff here.. editted for brevity... WAGTAIL_SITE_NAME = "mySite" AUTH_USER_MODEL = 'members.MyUser' Here's the trace back: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "C:\Python36\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python36\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python36\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Embed tweets using python django + Javascript
I'm trying to embed tweets using python django and javascript. This is my views.py currently: def tweets(request): context_dict = {} tweets_today = Tweet.objects.order_by('-favorites') tweets_today = tweets_today[:15] context_dict['tweets_today'] = tweets_today return render(request, 'summary/tweets.html', context_dict) And my HTML (base.html has the twitter JS script) {% extends 'base.html' %} {% block body_block %} <div class="container"> {% for tweet in tweets_today %} <div class="block social-block social-twitter"> <div id="container_{{ forloop.counter }}"> </div> <a href="#" class="btn btn-round btn-red"></a> </div> <script> window.onload = (function () { twttr.widgets.createTweet( '{{ tweet.tweet_id }}', document.getElementById('container_{{ forloop.counter }}'), { theme: 'dark' } ); }); </script> {% endfor %} </div> {% endblock %} For some reason this is only embedding one tweet. Is it because of the window.onload? -
Call function every time I add 'ManyRelatedObject'
I'm making a pizza application and the task is I have a different price for different size of pizza. And also, if I add a topping to pizza, the price gets bigger. I have a set_price function that sets the price for pizza. What I need to do is to call this set_price function every time I add a new topping and every time I create a new pizza object. class Topping(models.Model): name = models.CharField(max_length=64) def __str__(self): return f"{self.name}" class RegPizza(models.Model): size = models.CharField(max_length=5) price = 0 toppings = models.ManyToManyField(Topping, blank=True, related_name="inreg") def __str__(self): return f"Regular Pizza ({self.price}$)" def set_price(self): if self.size == 'Small': self.price = 12.20 if self.toppings.count() == 1: self.price = 13.20 if self.toppings.count() == 2: self.price = 14.70 if self.toppings.count() == 3: self.price = 15.70 if self.size == 'Large': self.price = 17.45 if self.toppings.count() == 1: self.price = 19.45 if self.toppings.count() == 2: self.price = 21.45 if self.toppings.count() == 3: self.price = 23.45 -
Is it possible to use JavaScript generated text from Django templates using the"with" templatetag
I am using JavaScript code to generate latitude and longitude results in my django templates. I was wondering if it was possible to use The results spat by the JavaScript to my django variables using the {% with ... %} template tag Below is my user.profile model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.DateField(blank=True, null=True) member_since = models.DateTimeField(auto_now_add=True) profile_image = models.ImageField(default='', blank=True, null=True) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) point = models.PointField(srid=4326, default='SRID=4326;POINT(0.0 0.0)') objects = models.GeoManager() -
Attribute error while running django-admin startproject
I am new to Django and trying to start a project using django-admin. I tried this before and it worked well but this time around it shows me this error and having searched online for the meaning of this error, I could not find anything meaningful. Steps- 1. I opened my command prompt and have already installed pip and django. I changed the directory and put in the command django-admin startproject mysite but it wouldnt work and gave me this error. class Clamped(_decimal.DecimalException): Attribute error : module 'decimal' has no attribute 'DecimalException' -
Django missing a migration in the 'auth' app
I'm trying to work on a Django project on a different computer than the one I usually do. However, when trying to run the following migration: from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0010_auto_20180727_1345'), ('lucy_web', '0183_auto_20180814_1505'), ] operations = [ migrations.CreateModel( name='GoogleCredentials', fields=[ ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('user', models.OneToOneField(limit_choices_to={'is_staff': True}, on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ('token', models.CharField(max_length=255, null=True)), ('refresh_token', models.CharField(max_length=255, null=True)), ('token_uri', models.CharField(max_length=255, null=True)), ('client_id', models.CharField(max_length=255, null=True)), ('client_secret', models.CharField(max_length=255, null=True)), ('scopes', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=255), null=True, size=None)), ], options={ 'abstract': False, }, ), ] I get this error message: django.db.migrations.exceptions.NodeNotFoundError: Migration lucy_web.0184_googlecredentials dependencies reference nonexistent parent node ('auth', '0010_auto_20180727_1345') Following https://groups.google.com/forum/#!topic/django-users/m59NufO1GI8, I went into the django/contrib/auth/migrations directory and found that indeed, there are 9 migrations, but the 10th migration is not there: Kurts-MacBook-Pro:auth kurtpeek$ ls migrations 0001_initial.py 0002_alter_permission_name_max_length.py 0003_alter_user_email_max_length.py 0004_alter_user_username_opts.py 0005_alter_user_last_login_null.py 0006_require_contenttypes_0002.py 0007_alter_validators_add_error_messages.py 0008_alter_user_username_max_length.py 0009_alter_user_last_name_max_length.py __init__.py __pycache__/ Kurts-MacBook-Pro:auth kurtpeek$ pwd /Users/kurtpeek/.local/share/virtualenvs/lucy-web-oCa8O1zi/lib/python3.7/site-packages/django/contrib/auth The problem is, I haven't checked the virtual env into version control, and I don't have access to the other computer at the moment. I also feel like I shouldn't have to check in the Django source code for the project, though. My question is: how did this situation likely come … -
How to inherit permissions on django class based views?
class ViewOne(TemplateView): permission_classes = (permissions.IsFoo,) class ViewTwo(TemplateView): permission_classes = (permissions.IsBar,) class ViewThree(ViewTwo): permission_classes = (permissions.IsXYZ,) On this example, how can ViewThree inherit permissions.IsBar from the parent view and hold both permissions.IsBar and permissions.IsXYZ? -
Nginx: 403 Forbidden nginx/1.12.1 (Ubuntu)
I've never before configured any production server, I'm trying to configure nginx and keep getting the 403 Forbidden error. I can't figure out the reason why it's happening. Here is a complete error report: [crit] 25145#25145: *1 connect() to unix:/home/albert/deploy_test/django_env /run/gunicorn.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.1.118, server: 192.168.1.118, request: "GET / HTTP/1.1", upstream: "http://unix:/home/albert/deploy_test/django_env /run/gunicorn.sock:/", host: "192.168.1.118" Here is my /etc/nginx/sites-available/deployproject.conf: (I removed the default config and created a symlink as follows: sudo ln -s /etc/nginx/sites-available/deployproject.conf /etc/nginx/sites-enabled/deployproject.conf) upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/albert/deploy_test/django_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 192.168.1.118; client_max_body_size 4G; access_log /home/albert/logs/nginx-access.log; error_log /home/albert/logs/nginx-error.log; location /static/ { alias /home/albert/static/; } location /media/ { alias /home/albert/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along … -
How do I suppose to fetch data from a specific room in Twilio?
Hello Awesome People! Get stuck while trying to configure a Video Chat with Twilio and Django I want to fetch data from a room, I realize that only the unique_name is present: Here is an example of what I am trying to do: # All stuff related to credentials are correct room_name = 'CoolTeam' room = client.video.rooms(room_name).fetch() print("room") print(room,0) print(room.unique_name,1) print(room.max_participants,2) print(room.duration,3) room.update('completed') # I tried destroying the room print(room.duration,4) print(room.end_time,5) print(room.date_created,6) print(duration,7) As I see in their documentation, the output may be a python dictionary This is the output <Twilio.Video.V1.RoomInstance sid=CoolTeam> 0 'CoolTeam' 1 50 2 None 3 None 4 None 5 2018-08-21 21:53:43+00:00 6 None 7 Basically I want to get the duration of the room, before or after the room is completed -
Rendering user specific data
Hi! I'm trying to create a webapp which renders data for the user specifically. I have to models, one for the user (djangos built in User) and one for the data to be rendered. My model ffor the user: class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return self.user.username My model for the data: class MyModel(models.Model): user_k = models.ForeignKey(User,related_name='RelatedName',on_delete=models.CASCADE) Date_Time = models.DateTimeField(default=timezone.now) DataOne = models.PositiveIntegerField(null=True) DataTwo = models.PositiveIntegerField(null=True) DataThree = models.PositiveIntegerField(null=True) In my views.py file i have this view for it: class MyView(DetailView): model = models.User context_object_name = 'mylist' template_name = 'my_app/example.html' def get_queryset(self): return User.objects.filter(user_k=self.request.user) And my problem that i can't solve is that I'm getting this error: Cannot query "user": Must be "MyModel" instance. I've googled it multiple times also tried the django documentation. My guess is that the problem might be in the my models, where my intention was to connect my second model to the username, but I'm not sure. Thanks for your help! -
How to change the width of a drop-down field in a django form using widget attributes not css
I am trying to make all of the fields in my django form have the same size to look tidy. I have text input, drop down and text area. I am creating the form using the Ticket model so I am not defining the form fields explicitly. I was able to resize the text input, but what is the attribute in a drop down field that controls the width? Note that the choices in the drop down are basically foreign keys from another table that are defined in the model. class NewTicket(forms.ModelForm): class Meta: model=Ticket fields = ('subject','business','project','description') widgets={ 'subject': forms.TextInput(attrs={'size': '20px'}), 'business': forms.Select(attrs={'width': '20px'}) #this line does not work } -
Django / Android Multipart Video File Upload
I'm working on both an Android app (Java) and the corresponding back end (Python / Django). In the app I record a MP4 file and save it to external storage. I then upload the MP4 file to my server, but currently this breaks my settings.DATA_UPLOAD_MAX_MEMORY_SIZE in Django. I can always increase that limit, but splitting the file into chunks seems like a good alternative. Can I split the video file into chunks and do a multipart upload from Android? How would I recombine these on the Python end to form one video file? This is a pretty vanilla single file upload now, but it's where I'm starting! Here's the Android code I'm using to upload the file: private void sendVideoFile(String filename) { Log.d(TAG, "Sending video from: " + filename); File file = new File(filename); int size = (int) file.length(); Log.d(TAG, "Video size: " + size); final byte[] video_bytes = new byte[size]; try { BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file)); buf.read(video_bytes, 0, video_bytes.length); buf.close(); String url ="http://my-server.herokuapp.com/upload_video"; Request stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject obj = new JSONObject(response); Log.d(TAG, response); } catch (JSONException e) { e.printStackTrace(); } finally { isProcessing … -
fix polygon coordinate order in geodjango
I'm importing a Census shapefile into a django project like: from django.contrib.gis.gdal import DataSource d = DataSource('data/tl_2017_us_state.shp') Docs: https://docs.djangoproject.com/en/1.11/ref/contrib/gis/gdal/#django.contrib.gis.gdal.DataSource But it seems that the source data has coordinates in longitude, latitude order, so for example: d[0].get_geoms()[0].coords (((-81.11055999999999, 39.472046), (-81.11039799999999, 39.472336), (-81.109926, 39.473163), (-81.10980699999999, 39.473371), (-81.109729, 39.473518999999996), ...),) When I want them in reverse, like (39, -81) So first question, why are they in this order rather than the (more conventional?) latitude, longitude? Is this a property of the Spatial Reference System of the source data? Second question, is there a param I can pass to DataSource which will cause it to put them in the order I want? Or, third question, am I accessing the coordinate points in the wrong way? Obviously I can manually correct this by iterating through all polygons and all points and rearranging them, but I want to understand why Census would provide them in this order in the first place. -
is it possible to use dropzone.js with a form with other fields in django?
I have a form that have 3 field, which is title, image and description. I want to use Dropzone.js instead of my normal imagefield because it can display the image and have the feature of drag and drop. But i cant make it happen if my form have other fields, it seem like you can only use the Dropzone if your forms only have one field(filefield or imagefield ) just for uploading file. this is my form but i want make something like this but with one more field description. The problem is i cant have other field inside the form if i want to use dropzone js. The Resource of django how to use Dropzone js combined with others fields in the form is lacking. i think this is the only documentary i can reference which is only explain how to use Dropzone.js in django if your forms only have one field which is filefield or imagefield just for uploading file, so if your forms have other field inside, seem like the dropzone wont work or maybe i miss something. If you have any suggestion of plugins or package i can install work similar like Dropzone JS, it will … -
django docker gadal path GDAL_LIBRARY_PATH (Is GDAL installed)
On my windows machine my settings shows: if os.name == 'nt': OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W #Hey there, got a problem? see reference above. os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] and all works great. Now, I wish to move this to my docker and my docker-compose looks like this: # docker-compose build # docker-compose up -d web version: '3' services: nginx: image: nginx:latest ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web redis: image: redis:latest ports: - '6379:6379' web: build: . depends_on: - db volumes: - ./src:/src expose: - "8000" links: - redis db: image: kartoza/postgis:10.0-2.4 volumes: - 'postgis-data:/var/lib/postgresql' environment: - POSTGRES_DB=my_db - POSTGRES_USER=user - POSTGRES_PASS=secret - ALLOW_IP_RANGE=0.0.0.0/0 ports: - 5432:5432 restart: unless-stopped pgadmin: links: - db:db image: fenglc/pgadmin4 volumes: - /data/pgadmin:/root/.pgadmin ports: - "5050:5050" restart: unless-stopped so 8 seconds after the docker-compose is up the web (dockerdjango_web) EXIT with the log-reason: from django.contrib.gis.gdal.driver import Driver File "/usr/local/lib/python3.6/site-packages/django/contrib/gis/gdal/driver.py", line 5, in <module> from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi File "/usr/local/lib/python3.6/site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 9, in <module> from django.contrib.gis.gdal.libgdal import …