README.rst 23.4 KB
Newer Older
1 2 3
django-rest-framework-gis
=========================

4
|Build Status| |Coverage Status| |Requirements Status| |PyPI version|
5 6

Geographic add-ons for Django Rest Framework - `Mailing
7
List <http://bit.ly/1M4sLTp>`__.
8

Federico Capoano's avatar
Federico Capoano committed
9 10
Install last stable version from pypi
-------------------------------------
11

Federico Capoano's avatar
Federico Capoano committed
12
.. code-block:: bash
13 14 15

    pip install djangorestframework-gis

Federico Capoano's avatar
Federico Capoano committed
16 17 18 19 20 21 22
Install development version
---------------------------

.. code-block:: bash

    pip install https://github.com/djangonauts/django-rest-framework-gis/tarball/master

23 24 25 26 27 28 29 30 31 32 33 34 35 36
Setup
-----

Add ``rest_framework_gis`` in ``settings.INSTALLED_APPS``, after ``rest_framework``:

.. code-block:: python

    INSTALLED_APPS = [
        # ...
        'rest_framework',
        'rest_framework_gis',
        # ...
    ]

37 38
Compatibility with DRF, Django and Python
-----------------------------------------
39

40
===============  ============================ ==================== ==================================
41
DRF-gis version  DRF version                  Django version       Python version
42
**0.13.x**       **3.3** to **3.8**           **1.11** to **2.0**   **2.7** to **3.6**
Federico Capoano's avatar
Federico Capoano committed
43 44
**0.12.x**       **3.1** to **3.7**           **1.11** to **2.0**   **2.7** to **3.6**
**0.11.x**       **3.1** to **3.6**           **1.7** to **1.11**  **2.7** to **3.6**
45 46
**0.10.x**       **3.1** to **3.3**           **1.7** to **1.9**   **2.7** to **3.5**
**0.9.6**        **3.1** to **3.2**           **1.5** to **1.8**   **2.6** to **3.5**
Federico Capoano's avatar
Federico Capoano committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
**0.9.5**        **3.1** to **3.2**           **1.5** to **1.8**   **2.6** to **3.4**
**0.9.4**        **3.1** to **3.2**           **1.5** to **1.8**   **2.6** to **3.4**
**0.9.3**        **3.1**                      **1.5** to **1.8**   **2.6** to **3.4**
**0.9.2**        **3.1**                      **1.5** to **1.8**   **2.6** to **3.4**
**0.9.1**        **3.1**                      **1.5** to **1.8**   **2.6** to **3.4**
**0.9**          **3.1**                      **1.5** to **1.8**   **2.6**, **2.7**, **3.3**, **3.4**
**0.9**          **3.1**                      **1.5** to **1.8**   **2.6**, **2.7**, **3.3**, **3.4**
**0.9**          **3.1**                      **1.5** to **1.8**   **2.6**, **2.7**, **3.3**, **3.4**
**0.8.2**        **3.0.4** to **3.1.1**       **1.5** to **1.8**   **2.6**, **2.7**, **3.3**, **3.4**
**0.8.1**        **3.0.4** to **3.1.1**       **1.5** to **1.8**   **2.6**, **2.7**, **3.3**, **3.4**
**0.8**          **3.0.4**                    **1.5** to **1.7**   **2.6**, **2.7**, **3.3**, **3.4**
**0.7**          **2.4.3**                    **1.5** to **1.7**   **2.6**, **2.7**, **3.3**, **3.4**
**0.6**          **2.4.3**                    **1.5** to **1.7**   **2.6**, **2.7**, **3.3**, **3.4**
**0.5**          from **2.3.14** to **2.4.2** **1.5** to **1.7**   **2.6**, **2.7**, **3.3**, **3.4**
**0.4**          from **2.3.14** to **2.4.2** **1.5** to **1.7**   **2.6**, **2.7**, **3.3**, **3.4**
**0.3**          from **2.3.14** to **2.4.2** **1.5**, **1.6**     **2.6**, **2.7**
**0.2**          from **2.2.2** to **2.3.13** **1.5**, **1.6**     **2.6**, **2.7**
64
===============  ============================ ==================== ==================================
65

66 67 68
Fields
------

69 70 71
GeometryField
~~~~~~~~~~~~~

72
Provides a ``GeometryField``, which is a subclass of Django Rest Framework
73 74 75 76
(from now on **DRF**) ``WritableField``. This field handles GeoDjango
geometry fields, providing custom ``to_native`` and ``from_native``
methods for GeoJSON input/output.

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
This field takes two optional arguments:

``precision``: Passes coordinates through Python's builtin ``round()`` function (`docs
<https://docs.python.org/3/library/functions.html#round>`_), rounding values to
the provided level of precision. E.g. A Point with lat/lng of
``[51.0486, -114.0708]`` passed through a ``GeometryField(precision=2)``
would return a Point with a lat/lng of ``[51.05, -114.07]``.

``remove_duplicates``: Remove sequential duplicate coordinates from line and
polygon geometries. This is particularly useful when used with the ``precision``
argument, as the likelihood of duplicate coordinates increase as precision of
coordinates are reduced.

**Note:** While both above arguments are designed to reduce the
byte size of the API response, they will also increase the processing time
required to render the response. This will likely be negligible for small GeoJSON
responses but may become an issue for large responses.

95 96 97
**New in 0.9.3:** there is no need to define this field explicitly in your serializer,
it's mapped automatically during initialization in ``rest_framework_gis.apps.AppConfig.ready()``.

98 99 100
GeometrySerializerMethodField
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

101 102 103
Provides a ``GeometrySerializerMethodField``, which is a subclass of DRF
``SerializerMethodField`` and handles values which are computed with a serializer
method and are used as a ``geo_field``. `See example below <https://github.com/djangonauts/django-rest-framework-gis#using-geometryserializermethodfield-as-geo_field>`__.
104

105 106 107
Serializers
-----------

108 109 110 111 112
GeoModelSerializer (DEPRECATED)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**Deprecated, will be removed in 1.0**: Using this serializer is not needed anymore since 0.9.3 if you add
``rest_framework_gis`` in ``settings.INSTALLED_APPS``
113

114
Provides a ``GeoModelSerializer``, which is a subclass of DRF
115 116 117 118 119 120
``ModelSerializer``. This serializer updates the field\_mapping
dictionary to include field mapping of GeoDjango geometry fields to the
above ``GeometryField``.

For example, the following model:

Federico Capoano's avatar
Federico Capoano committed
121
.. code-block:: python
122 123 124 125 126 127 128 129 130 131

    class Location(models.Model):
        """
        A model which holds information about a particular location
        """
        address = models.Charfield(max_length=255)
        city = models.CharField(max_length=100)
        state = models.CharField(max_length=100)
        point = models.PointField()

Federico Capoano's avatar
Federico Capoano committed
132
By default, the DRF ModelSerializer will output:
133

Federico Capoano's avatar
Federico Capoano committed
134
.. code-block:: javascript
135 136 137 138 139 140 141 142 143

    {
        "id": 1,
        "address": "742 Evergreen Terrace",
        "city":  "Springfield",
        "state": "Oregon",
        "point": "POINT(-123.0208 44.0464)"
    }

Martin Feige's avatar
Martin Feige committed
144
In contrast, the ``GeoModelSerializer`` will output:
145

Federico Capoano's avatar
Federico Capoano committed
146
.. code-block:: javascript
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    {
        "id": 1,
        "address": "742 Evergreen Terrace",
        "city":  "Springfield",
        "state": "Oregon",
        "point": {
            "type": "Point",
            "coordinates": [-123.0208, 44.0464],
        }
    }

GeoFeatureModelSerializer
~~~~~~~~~~~~~~~~~~~~~~~~~

162
``GeoFeatureModelSerializer`` is a subclass of ``rest_framework.ModelSerializer``
163 164 165
which will output data in a format that is **GeoJSON** compatible. Using
the above example, the ``GeoFeatureModelSerializer`` will output:

Federico Capoano's avatar
Federico Capoano committed
166
.. code-block:: javascript
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

     {
        "id": 1,
        "type": "Feature",
        "geometry": {
            "point": {
                "type": "Point",
                "coordinates": [-123.0208, 44.0464],
            },
        },
        "properties": {
            "address": "742 Evergreen Terrace",
            "city":  "Springfield",
            "state": "Oregon"
        }
    }

If you are serializing an object list, ``GeoFeatureModelSerializer``
will create a ``FeatureCollection``:

Federico Capoano's avatar
Federico Capoano committed
187
.. code-block:: javascript
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223

    {
        "type": "FeatureCollection",
        "features": [
        {
            "id": 1
            "type": "Feature",
            "geometry": {
                "point": {
                    "type": "Point",
                    "coordinates": [-123.0208, 44.0464],
                }
            },
            "properties": {
                "address": "742 Evergreen Terrace",
                "city":  "Springfield",
                "state": "Oregon",
            }
        }
        {
            "id": 2,
            "type": "Feature",
            "geometry": {
                "point": {
                    "type": "Point",
                    "coordinates": [-123.0208, 44.0489],
                },
            },
            "properties": {
                "address": "744 Evergreen Terrace",
                "city":  "Springfield",
                "state": "Oregon"
            }
        }
    }

224 225 226
Specifying the geometry field: "geo_field"
##########################################

Federico Capoano's avatar
Federico Capoano committed
227
``GeoFeatureModelSerializer`` requires you to define a ``geo_field``
228 229
to be serialized as the "geometry". For example:

Federico Capoano's avatar
Federico Capoano committed
230
.. code-block:: python
231

232
    from rest_framework_gis.serializers import GeoFeatureModelSerializer
233 234 235 236 237 238 239 240 241 242 243 244

    class LocationSerializer(GeoFeatureModelSerializer):
        """ A class to serialize locations as GeoJSON compatible data """

        class Meta:
            model = Location
            geo_field = "point"

            # you can also explicitly declare which fields you want to include
            # as with a ModelSerializer.
            fields = ('id', 'address', 'city', 'state')

245 246 247
Using GeometrySerializerMethodField as "geo_field"
##################################################

Federico Capoano's avatar
Federico Capoano committed
248
``geo_field`` may also be an instance of ``GeometrySerializerMethodField``.
249
In this case you can compute its value during serialization. For example:
250 251 252

.. code-block:: python

253
    from django.contrib.gis.geos import Point
254 255 256 257 258
    from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField

    class LocationSerializer(GeoFeatureModelSerializer):
        """ A class to serialize locations as GeoJSON compatible data """

259
        # a field which contains a geometry value and can be used as geo_field
260 261 262
        other_point = GeometrySerializerMethodField()

        def get_other_point(self, obj):
263
            return Point(obj.point.lat / 2, obj.point.lon / 2)
264 265 266 267 268

        class Meta:
            model = Location
            geo_field = 'other_point'

petr's avatar
petr committed
269 270
Serializer for ``geo_field`` may also return ``None`` value, which will translate to ``null`` value for geojson ``geometry`` field.

271 272
Specifying the ID: "id_field"
#############################
273

274
The primary key of the model (usually the "id" attribute) is
275 276 277 278 279
automatically used as the ``id`` field of each
`GeoJSON Feature Object <https://tools.ietf.org/html/draft-butler-geojson#section-2.2>`_.

The default behaviour follows the `GeoJSON RFC <https://tools.ietf.org/html/draft-butler-geojson>`_,
but it can be disbaled by setting ``id_field`` to ``False``:
280

Federico Capoano's avatar
Federico Capoano committed
281
.. code-block:: python
282

283
    from rest_framework_gis.serializers import GeoFeatureModelSerializer
284 285 286 287 288 289 290 291 292

    class LocationSerializer(GeoFeatureModelSerializer):

        class Meta:
            model = Location
            geo_field = "point"
            id_field = False
            fields = ('id', 'address', 'city', 'state')

293
The ``id_field`` can also be set to use some other unique field in your model, eg: ``slug``:
294

Federico Capoano's avatar
Federico Capoano committed
295
.. code-block:: python
296

297
    from rest_framework_gis.serializers import GeoFeatureModelSerializer
298 299 300 301 302

    class LocationSerializer(GeoFeatureModelSerializer):

        class Meta:
            model = Location
303 304
            geo_field = 'point'
            id_field = 'slug'
305 306
            fields = ('slug', 'address', 'city', 'state')

307 308 309
Bounding Box: "auto_bbox" and "bbox_geo_field"
##############################################

310 311
The GeoJSON specification allows a feature to contain a
`boundingbox of a feature <http://geojson.org/geojson-spec.html#geojson-objects>`__.
312
``GeoFeatureModelSerializer`` allows two different ways to fill this property. The first
Federico Capoano's avatar
Federico Capoano committed
313 314
is using the ``geo_field`` to calculate the bounding box of a feature. This only allows
read access for a REST client and can be achieved using ``auto_bbox``. Example:
315 316 317 318 319 320 321 322 323

.. code-block:: python

    from rest_framework_gis.serializers import GeoFeatureModelSerializer

    class LocationSerializer(GeoFeatureModelSerializer):
        class Meta:
            model = Location
            geo_field = 'geometry'
324
            auto_bbox = True
325 326


Edward Betts's avatar
Edward Betts committed
327
The second approach uses the ``bbox_geo_field`` to specify an additional
328
``GeometryField`` of the model which will be used to calculate the bounding box. This allows
329
boundingboxes differ from the exact extent of a features geometry. Additionally this
330 331 332 333 334 335 336 337 338 339 340 341 342 343
enables read and write access for the REST client. Bounding boxes send from the client will
be saved as Polygons. Example:

.. code-block:: python

    from rest_framework_gis.serializers import GeoFeatureModelSerializer

    class LocationSerializer(GeoFeatureModelSerializer):

        class Meta:
            model = BoxedLocation
            geo_field = 'geometry'
            bbox_geo_field = 'bbox_geometry'

344 345 346 347

Custom GeoJSON properties source
################################

Federico Capoano's avatar
Federico Capoano committed
348
In GeoJSON each feature can have a ``properties`` member containing the
349 350
attributes of the feature. By default this field is filled with the
attributes from your Django model, excluding the id, geometry and bounding
Federico Capoano's avatar
Federico Capoano committed
351 352
box fields. It's possible to override this behaviour and implement a custom
source for the ``properties`` member.
353

Federico Capoano's avatar
Federico Capoano committed
354 355
The following example shows how to use a PostgreSQL HStore field as a source for
the ``properties`` member:
356 357 358 359 360 361

.. code-block:: python

    # models.py
    class Link(models.Model):
        """
Federico Capoano's avatar
Federico Capoano committed
362 363
        Metadata is stored in a PostgreSQL HStore field, which allows us to
        store arbitrary key-value pairs with a link record.
364
        """
Germán Larraín's avatar
Germán Larraín committed
365
        metadata = HStoreField(blank=True, null=True, default=dict)
366 367 368 369 370 371 372 373 374 375
        geo = models.LineStringField()
        objects = models.GeoManager()

    # serializers.py
    class NetworkGeoSerializer(GeoFeatureModelSerializer):
        class Meta:
            model = models.Link
            geo_field = 'geo'
            auto_bbox = True

376
        def get_properties(self, instance, fields):
Federico Capoano's avatar
Federico Capoano committed
377 378
            # This is a PostgreSQL HStore field, which django maps to a dict
            return instance.metadata
379 380

        def unformat_geojson(self, feature):
Federico Capoano's avatar
Federico Capoano committed
381
            attrs = {
382 383 384 385 386
                self.Meta.geo_field: feature["geometry"],
                "metadata": feature["properties"]
            }

            if self.Meta.bbox_geo_field and "bbox" in feature:
Federico Capoano's avatar
Federico Capoano committed
387
                attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature["bbox"])
388

Federico Capoano's avatar
Federico Capoano committed
389
            return attrs
390 391

When the serializer renders GeoJSON, it calls the method
392
``get_properties`` for each object in the database. This function
393 394 395 396 397 398 399 400
should return a dictionary containing the attributes for the feature. In the
case of a HStore field, this function is easily implemented.

The reverse is also required: mapping a GeoJSON formatted structure to
attributes of your model. This task is done by ``unformat_geojson``. It should
return a dictionary with your model attributes as keys, and the corresponding
values retrieved from the GeoJSON feature data.

Federico Capoano's avatar
Federico Capoano committed
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
Pagination
----------

We provide a ``GeoJsonPagination`` class.

GeoJsonPagination
~~~~~~~~~~~~~~~~~

Based on ``rest_framework.pagination.PageNumberPagination``.

Code example:

.. code-block:: python

    from rest_framework_gis.pagination import GeoJsonPagination
    # --- other omitted imports --- #

    class GeojsonLocationList(generics.ListCreateAPIView):
        # -- other omitted view attributes --- #
        pagination_class = GeoJsonPagination

Example result response (cut to one element only instead of 10):

.. code-block:: javascript

    {
        "type": "FeatureCollection",
        "count": 25,
        "next": "http://localhost:8000/geojson/?page=2",
        "previous": null,
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        42.0,
                        50.0
                    ]
                },
                "properties": {
                    "name": "test"
                }
            }
        ]
    }


449 450 451
Filters
-------

452 453
**note**: this feature has been tested up to django-filter 1.0.

454
We provide a ``GeometryFilter`` field as well as a ``GeoFilterSet``
455 456 457 458 459 460 461
for usage with ``django_filter``. You simply provide, in the query
string, one of the textual types supported by ``GEOSGeometry``. By
default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON.

GeometryFilter
~~~~~~~~~~~~~~

Federico Capoano's avatar
Federico Capoano committed
462
.. code-block:: python
463

464
    from rest_framework_gis.filterset import GeoFilterSet
465 466
    from rest_framework_gis.filters import GeometryFilter
    from django_filters import filters
467 468

    class RegionFilter(GeoFilterSet):
469
        slug = filters.CharFilter(name='slug', lookup_expr='istartswith')
470
        contains_geom = GeometryFilter(name='geom', lookup_expr='contains')
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

        class Meta:
            model = Region

We can then filter in the URL, using GeoJSON, and we will perform a
``__contains`` geometry lookup, e.g.
``/region/?contains_geom={ "type": "Point", "coordinates": [ -123.26436996459961, 44.564178042345375 ] }``.

GeoFilterSet
~~~~~~~~~~~~

The ``GeoFilterSet`` provides a ``django_filter`` compatible
``FilterSet`` that will automatically create ``GeometryFilters`` for
``GeometryFields``.

486
InBBoxFilter
487 488
~~~~~~~~~~~~

489
Provides a ``InBBoxFilter``, which is a subclass of DRF
490 491 492
``BaseFilterBackend``. Filters a queryset to only those instances within
a certain bounding box.

493 494

``views.py:``
alexdebrie's avatar
alexdebrie committed
495

496 497
.. code-block:: python

498
    from rest_framework_gis.filters import InBBoxFilter
499 500 501

    class LocationList(ListAPIView):

alexdebrie's avatar
alexdebrie committed
502 503 504
        queryset = models.Location.objects.all()
        serializer_class = serializers.LocationSerializer
        bbox_filter_field = 'point'
505
        filter_backends = (InBBoxFilter, )
alexdebrie's avatar
alexdebrie committed
506
        bbox_filter_include_overlapping = True # Optional
507

Jeff Johnson's avatar
Jeff Johnson committed
508 509
We can then filter in the URL, using Bounding Box format (min Lon, min
Lat, max Lon, max Lat), and we can search for instances within the
510 511 512
bounding box, e.g.:
``/location/?in_bbox=-90,29,-89,35``.

513 514 515
By default, InBBoxFilter will only return those instances entirely
within the stated bounding box. To include those instances which overlap
the bounding box, include ``bbox_filter_include_overlapping = True``
516 517
in your view.

518
Note that if you are using other filters, you'll want to include your
519 520
other filter backend in your view. For example:

521
``filter_backends = (InBBoxFilter, DjangoFilterBackend,)``
522

Jesse Crocker's avatar
Jesse Crocker committed
523
TMSTileFilter
524
~~~~~~~~~~~~~
Jesse Crocker's avatar
Jesse Crocker committed
525

526
Provides a ``TMSTileFilter``, which is a subclass of ``InBBoxFilter``.
527
Filters a queryset to only those instances within a bounding box defined
528
by a `TMS tile <http://wiki.openstreetmap.org/wiki/TMS>`__ address.
Jesse Crocker's avatar
Jesse Crocker committed
529 530 531 532 533 534 535 536 537 538 539 540

``views.py:``

.. code-block:: python

    from rest_framework_gis.filters import TMSTileFilter

    class LocationList(ListAPIView):

        queryset = models.Location.objects.all()
        serializer_class = serializers.LocationSerializer
        bbox_filter_field = 'point'
541
        filter_backends = (TMSTileFilter, )
Jesse Crocker's avatar
Jesse Crocker committed
542 543
        bbox_filter_include_overlapping = True # Optional

544
We can then filter in the URL, using TMS tile addresses in the zoom/x/y format,
Jesse Crocker's avatar
Jesse Crocker committed
545 546
eg:.
``/location/?tile=8/100/200``
547
which is equivalant to filtering on the bbox  (-39.37500,-71.07406,-37.96875,-70.61261).
Jesse Crocker's avatar
Jesse Crocker committed
548

549
For more information on configuration options see InBBoxFilter.
Jesse Crocker's avatar
Jesse Crocker committed
550

551
Note that the tile address start in the upper left, not the lower left origin used by some
Jesse Crocker's avatar
Jesse Crocker committed
552 553
implementations.

554
DistanceToPointFilter
555
~~~~~~~~~~~~~~~~~~~~~
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

Provides a ``DistanceToPointFilter``, which is a subclass of DRF
``BaseFilterBackend``. Filters a queryset to only those instances within
a certain distance of a given point.

``views.py:``

.. code-block:: python

    from rest_framework_gis.filters import DistanceToPointFilter

    class LocationList(ListAPIView):

        queryset = models.Location.objects.all()
        serializer_class = serializers.LocationSerializer
        distance_filter_field = 'geometry'
572
        filter_backends = (DistanceToPointFilter, )
573 574 575
        bbox_filter_include_overlapping = True # Optional

We can then filter in the URL, using a distance and a point in (lon, lat) format. The
576
distance can be given in meters or in degrees.
577 578

eg:.
579
``/location/?dist=4000&point=-122.4862,37.7694&format=json``
580 581 582 583
which is equivalant to filtering within 4000 meters of the point  (-122.4862, 37.7694).

By default, DistanceToPointFilter will pass the 'distance' in the URL directly to the database for the search.
The effect depends on the srid of the database in use. If geo data is indexed in meters (srid 3875, aka 900913), a
584 585
distance in meters can be passed in directly without conversion. For lat-lon databases such as srid 4326,
which is indexed in degrees, the 'distance' will be interpreted as degrees. Set the flag, 'distance_filter_convert_meters'
586
to 'True' in order to convert an input distance in meters to degrees. This conversion is approximate, and the errors
587
at latitudes > 60 degrees are > 25%.
588

Federico Capoano's avatar
Federico Capoano committed
589
Projects using this package
590
---------------------------
Federico Capoano's avatar
Federico Capoano committed
591 592 593

- `Nodeshot <https://github.com/ninuxorg/nodeshot>`__: Extensible Django web application for management of community-led georeferenced data

594 595 596
Running the tests
-----------------

597 598 599 600 601 602 603 604
Required setup
==============

You need one of the `Spatial Database servers supported by
GeoDjango <https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#module-django.contrib.gis.db.backends>`__,
and create a database for the tests.

The following can be used with PostgreSQL:
605

Federico Capoano's avatar
Federico Capoano committed
606
.. code-block:: bash
607

608 609
  createdb django_restframework_gis
  psql -U postgres -d django_restframework_gis -c "CREATE EXTENSION postgis"
610 611 612 613 614 615

You might need to tweak the DB settings according to your DB
configuration. You can copy the file ``local_settings.example.py`` to
``local_settings.py`` and change the ``DATABASES`` and/or
``INSTALLED_APPS`` directives there.

616
This should allow you to run the tests already.
617

618 619
For reference, the following steps will setup a development environment for
contributing to the project:
620 621 622 623 624 625

-  create a spatial database named "django\_restframework\_gis"
-  create ``local_settings.py``, eg:
   ``cp local_settings.example.py local_settings.py``
-  tweak the ``DATABASES`` configuration directive according to your DB
   settings
gandhi23's avatar
gandhi23 committed
626
-  uncomment ``INSTALLED_APPS``
627 628 629 630
-  run ``python manage.py syncdb``
-  run ``python manage.py collectstatic``
-  run ``python manage.py runserver``

631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
Using tox
=========

The recommended way to run the tests is by using
`tox <https://tox.readthedocs.io/en/latest/>`__, which can be installed using
`pip install tox`.

You can use ``tox -l`` to list the available environments, and then e.g. use
the following to run all tests with Python 3.6 and Django 1.11:

.. code-block:: bash

    tox -e py36-django111

By default Django's test runner is used, but there is a variation of tox's
envlist to use pytest (using the ``-pytest`` suffix).

You can pass optional arguments to the test runner like this:

.. code-block:: bash

    tox -e py36-django111-pytest -- -k test_foo

Running tests manually
======================

Please refer to the ``tox.ini`` file for reference/help in case you want to run
tests manually / without tox.

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
Contributing
------------

1. Join the `Django REST Framework GIS Mailing
   List <https://groups.google.com/forum/#!forum/django-rest-framework-gis>`__
   and announce your intentions
2. Follow the `PEP8 Style Guide for Python
   Code <http://www.python.org/dev/peps/pep-0008/>`__
3. Fork this repo
4. Write code
5. Write tests for your code
6. Ensure all tests pass
7. Ensure test coverage is not under 90%
8. Document your changes
9. Send pull request

676
.. |Build Status| image:: https://travis-ci.org/djangonauts/django-rest-framework-gis.svg?branch=master
677
   :target: https://travis-ci.org/djangonauts/django-rest-framework-gis
678
.. |Coverage Status| image:: https://coveralls.io/repos/djangonauts/django-rest-framework-gis/badge.svg
679
   :target: https://coveralls.io/r/djangonauts/django-rest-framework-gis
680
.. |Requirements Status| image:: https://requires.io/github/djangonauts/django-rest-framework-gis/requirements.svg?branch=master
681
   :target: https://requires.io/github/djangonauts/django-rest-framework-gis/requirements/?branch=master
682
.. |PyPI version| image:: https://badge.fury.io/py/djangorestframework-gis.svg
683
   :target: http://badge.fury.io/py/djangorestframework-gis