I am developing a web app in geodjango (django) framework but I need to import raster files.
Is it possible a geodjango app read raster files from a directory?
GeoDjango does not currently support raster files. GeoDjango builds on top of the Geospatial Data Abstraction Library (GDAL) and, "currently, GeoDjango only supports GDAL's vector data capabilities" (strictly speaking, it supports the OGR library, a component of GDAL). Even if your database supports raster data, there are no Python hooks into that functionality provided by GeoDjango.
However, you can still work with raster data in a Python framework that includes GeoDjango. You'll just need another tool for working with raster data, such as rasterio, raster2pgsql, or by using the Python bindings for GDAL. If you wish to store raster data in a database, be aware that few databases will allow you to store raster data as anything other than a BLOB. If your database is PostgreSQL with PostGIS 2.0 or higher, you can store and even manipulate raster data with queries. A potential use case of GeoDjango with PostGIS 2.0+ in a Django view might look like:
from django.db import connection from django.http import HttpResponse cursor = connection.cursor() def respond_with_a_raster(request): # Write some SELECT query on raster data cursor.execute("SELECT ST_AsGDALRaster(rast, 'GTiff') FROM my_rasters") # Get a list of buffer objects out result = [ row for row in cursor.fetchall() ] # If expecting just one raster, unwrap until a buffer is found while type(result) != buffer: result = result response = HttpResponse(result, content_type='image/tiff') response['Content-Disposition'] = 'attachment; filename=raster.tiff') return response
Again, as GeoDjango doesn't recognize raster manipulation functionality in the database, you'll need to perform raw SQL queries with Django.
The code example above just delivers the raster as a file attachment. For displaying rasters on the front-end (browser-side) of your web application, you'll need a way to display raster data, but that is another discussion (e.g. about Web Map Services, WMS such as GeoServer or MapServer).
I started working on developing some raster functionality within Django. There are two packages that I am working on, one that allows loading raster data into Django, and another one that allows serving raster through a Tile Map Service or a Web Map Service.
Here is a page that uses these packages for raster rendering through Leaflet (as xyz tile layers).
Please take all of this with a grain of salt. The python packages are in early stage development, so please take that into consideration if you want to try them out. Any feedback would be appreciated of course. And apologies for the self-advertising, but I figured this might be interesting for some of you.
As of version 1.8, GeoDjango does support raster data handled by GDAL. https://docs.djangoproject.com/en/1.8/ref/contrib/gis/gdal/