장고 - Location Field 학습

  • 이번 포스트에서는 django에서 location field를 추가하는 방법에 대해 알아볼 것이다.
  • 여기에서는 google map api를 연동하여 location field를 구현할 것이다.

Django Location Field 구현

ex) extore_project

1. django-location-field 모듈 설치

  • pip install django-location-field

2. 설정 파일 작성

  • 경로 : config > settings.py
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    INSTALLED_APPS = [
    ...
    'location_field.apps.DefaultConfig',
    ]

    from django.conf import settings
    LOCATION_FIELD_PATH = settings.STATIC_URL + 'location_field'

    LOCATION_FIELD = {
    'map.provider': 'google',
    'map.zoom': 13,

    'search.provider': 'google',
    'search.suffix': '',

    # Google
    'provider.google.api': '//maps.google.com/maps/api/js?sensor=false',
    'provider.google.api_key': '발급받은 구글 맵 api key 입력',
    'provider.google.api_libraries': '',
    'provider.google.map.type': 'ROADMAP',

    # misc
    'resources.root_path': LOCATION_FIELD_PATH,
    'resources.media': {
    'js': (
    LOCATION_FIELD_PATH + '/js/jquery.livequery.js',
    LOCATION_FIELD_PATH + '/js/form.js',
    ),
    },
    }

3. 모델 작성

  • 경로 : post > models.py
    1
    2
    3
    4
    5
    6
    from django.db import models
    from location_field.models.plain import PlainLocationField

    class Place(models.Model):
    city = models.CharField(max_length=255)
    location = PlainLocationField(based_fields=['city'], zoom=7)

4. 템플릿에서 지도 render

  • 경로 : post > templates > post > ***.html
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    {{form.media}}
    </head>
    <body>
    {{form}}
    </body>
    </html>