---
title: "GeoDjango 表单 API"
version: 6.1
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/6.1/ref/contrib/gis/forms-api/
canonical: https://djangodocs.dev/zh-hans/6.1/ref/contrib/gis/forms-api/
---
# GeoDjango 表单 API

GeoDjango 提供了一些专门的表单字段和小部件，以便在地图上可视化显示和编辑地理位置数据。默认情况下，它们使用由 [NASA](https://www.earthdata.nasa.gov/) 提供的基本 WMS 图层，并由 [OpenLayers](https://openlayers.org/) 驱动的地图。

## 字段参数

除了常规的 [表单字段参数](/zh-hans/6.1/ref/forms/fields/#core-field-arguments) 之外，GeoDjango 表单字段还接受以下可选参数。

### `srid`

#### `Field.srid`

这是字段值应该转换为的 SRID 代码。例如，如果地图小部件的 SRID 与您的应用程序或数据库通常使用的 SRID 不同，该字段将自动将输入值转换为该 SRID。

### `geom_type`

#### `Field.geom_type`

通常情况下，您不应该设置或更改该属性，它应该根据字段类进行设置。它与 OpenGIS 标准的几何名称相匹配。

### `max_geom_collections`

#### `Field.max_geom_collections`

> **New in Django 5.2.17**

The maximum number of geometry collections the field accepts before
refusing to parse the input and raising a
[`ValidationError`](/zh-hans/6.1/ref/exceptions/#django.core.exceptions.ValidationError). This guards against crashes
in the underlying GEOS library when parsing deeply nested
`GEOMETRYCOLLECTION` input. It defaults to `198`.

The limit is applied differently depending on the input format: for
well-known text (WKT) it bounds the nesting *depth*, while for well-known
binary (WKB and hex-encoded WKB) it bounds the *total* number of geometry
collections (both breadth and depth). As a result, the same value may
accept a wide, shallow collection as WKT but reject it as WKB. For GeoJSON,
the limit is not applied at all, since GDAL parses that input type instead.

Increase this value (or set to `None`) only if you must accept
legitimately deep geometries, since doing so reduces protection against
fatal errors.

## 表单字段类

### `GeometryField`

#### `class GeometryField`

### `PointField`

#### `class PointField`

### `LineStringField`

#### `class LineStringField`

### `PolygonField`

#### `class PolygonField`

### `MultiPointField`

#### `class MultiPointField`

### `MultiLineStringField`

#### `class MultiLineStringField`

### `MultiPolygonField`

#### `class MultiPolygonField`

### `GeometryCollectionField`

#### `class GeometryCollectionField`

## 表单部件

GeoDjango 表单小部件允许您在可视地图上显示和编辑地理数据。请注意，目前没有任何可用的小部件支持 3D 几何形状，因此对于这种类型的数据，几何字段将使用 `Textarea` 小部件作为回退。

### 表单属性

GeoDjango 的小部件是基于模板的，因此它们的属性大部分与其他 Django 小部件的属性不同。

#### `BaseGeometryWidget.base_layer`

> **New in Django 6.0**

A string that specifies the identifier for the default base map layer to be
used by the corresponding JavaScript map widget. It is passed as part of
the widget options when rendering, allowing the `MapWidget` to determine
which map tile provider or base layer to initialize (default is `None`).

#### `BaseGeometryWidget.geom_type`

OpenGIS 几何类型，通常由表单字段设置。

#### `BaseGeometryWidget.map_srid`

地图使用的 SRID 代码（默认为 4326）。

#### `BaseGeometryWidget.display_raw`

布尔值，指定是否可见一个文本区域输入框，显示当前几何形状的序列化表示，主要用于调试目的（默认为 `False`）。

#### `BaseGeometryWidget.supports_3d`

指示小部件是否支持编辑 3D 数据的属性（默认为 `False`）。

#### `BaseGeometryWidget.template_name`

用于呈现地图小部件的模板。

您可以以与任何其他 Django 小部件相同的方式传递小部件属性。例如：

```
from django.contrib.gis import forms

class MyGeoForm(forms.Form):
    point = forms.PointField(widget=forms.OSMWidget(attrs={"display_raw": True}))
```

### 部件类

`BaseGeometryWidget`

#### `class BaseGeometryWidget`

This is an abstract base widget containing the logic needed by subclasses.
You cannot directly use this widget for a geometry field.
Note that the rendering of GeoDjango widgets is based on a base layer name,
identified by the [`base_layer`](#django.contrib.gis.forms.widgets.BaseGeometryWidget.base_layer) class attribute.

`OpenLayersWidget`

#### `class OpenLayersWidget`

This is the default widget used by all GeoDjango form fields. Attributes
are:

#### `base_layer`

> **New in Django 6.0**

`nasaWorldview`

#### `template_name`

`gis/openlayers.html`.

#### `map_srid`

`3857`

`OpenLayersWidget` and [`OSMWidget`](#django.contrib.gis.forms.widgets.OSMWidget) include the `ol.js` and
`ol.css` files hosted on the `cdn.jsdelivr.net` content-delivery
network. These files can be overridden by subclassing the widget and
setting the `js` and `css` properties of the inner `Media` class (see
[资源作为静态定义](/zh-hans/6.1/topics/forms/media/#assets-as-a-static-definition)).

> **External assets with CSP**
>
> When [`ContentSecurityPolicyMiddleware`](/zh-hans/6.1/ref/middleware/#django.middleware.csp.ContentSecurityPolicyMiddleware) is
> enabled, the default OpenLayers CDN assets (`ol.js` and `ol.css`)
> will be blocked unless explicitly allowed. This can be addressed in one
> of two ways: **serve assets locally** by subclassing the widget and
> provide local copies of the JavaScript and CSS files, or
> **allow the CDN in the CSP policy**.
>
> For example, to allow the default NASA Worldview base layer (replace
> `x.y.z` with the actual version):
>
> ```
> from django.utils.csp import CSP
>
> SECURE_CSP = {
>     "default-src": [CSP.SELF],
>     "script-src": [CSP.SELF, "https://cdn.jsdelivr.net/npm/ol@x.y.z/dist/ol.js"],
>     "style-src": [CSP.SELF, "https://cdn.jsdelivr.net/npm/ol@x.y.z/ol.css"],
>     "img-src": [CSP.SELF, "https://*.earthdata.nasa.gov"],
> }
> ```

`OSMWidget`

#### `class OSMWidget`

This widget specialized [`OpenLayersWidget`](#django.contrib.gis.forms.widgets.OpenLayersWidget) and uses an OpenStreetMap
base layer to display geographic objects on. Attributes are:

#### `base_layer`

> **New in Django 6.0**

`osm`

#### `default_lat`

#### `default_lon`

默认的中心纬度和经度分别是 `47` 和 `5`，这是法国东部的一个位置。

#### `default_zoom`

默认的地图缩放级别是 `12`。

The [`OpenLayersWidget`](#django.contrib.gis.forms.widgets.OpenLayersWidget) note about using external assets also applies
here. See also this [FAQ answer](https://help.openstreetmap.org/questions/10920/how-to-embed-a-map-in-my-https-site) about `https` access to map tiles.

> **OpenStreetMap tiles with CSP**
>
> This widget uses OpenStreetMap tiles instead of NASA Worldview. If
> [Content Security Policy](/zh-hans/6.1/topics/security/#security-csp) enabled, both the OpenLayers CDN resources (as
> required by [`OpenLayersWidget`](#django.contrib.gis.forms.widgets.OpenLayersWidget)) and the OpenStreetMap tile
> servers must be allowed:
>
> ```
> from django.utils.csp import CSP
>
> SECURE_CSP = {
>     # other directives
>     "img-src": [CSP.SELF, "https://tile.openstreetmap.org"],
> }
> ```

> **Changed in Django 6.0**
>
> The `OSMWidget` no longer uses a custom template. Consequently, the
> `gis/openlayers-osm.html` template was removed.

### Customizing the base layer used in OpenLayers-based widgets

> **New in Django 6.0**

To customize the base layer displayed in OpenLayers-based geometry widgets,
define a new layer builder in a custom JavaScript file. For example:

*`path-to-file.js`*

```javascript
 MapWidget.layerBuilder.custom_layer_name = function () {
     // Return an OpenLayers layer instance.
     return new ol.layer.Tile({source: new ol.source.<ChosenSource>()});
 };
```

Then, subclass a standard geometry widget and set the `base_layer`:

```
from django.contrib.gis.forms.widgets import OpenLayersWidget

class YourCustomWidget(OpenLayersWidget):
    base_layer = "custom_layer_name"

    class Media:
        js = ["path-to-file.js"]
```
