Автозаполнение адреса в Django CreateView - PullRequest
0 голосов
/ 19 сентября 2019

Хорошо, мне нужна помощь.Я пытаюсь, чтобы поле адреса из формы CreateView автоматически заполнялось результатами API Places.Итак, я вижу 2 варианта:

  1. Переопределить поле адреса в CreateView.Используйте адрес ввода для API Адресов в качестве ввода в поле адреса для моей модели.
  2. Автозаполнение поля адреса в форме на основе результатов ввода адреса (поиск API Адресов).

Любые предложения будут с благодарностью.Я пробовал несколько разных опций и не могу заставить его работать правильно.

Спасибо.

autocomple.html

var placeSearch, autocomplete;

var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete() {
  // Create the autocomplete object, restricting the search predictions to
  // geographical location types.
  autocomplete = new google.maps.places.Autocomplete(
      document.getElementById('autocomplete'), {types: ['geocode']});

  // Avoid paying for data that you don't need by restricting the set of
  // place fields that are returned to just the address components.
  autocomplete.setFields(['address_component']);

  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
  autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
  console.log(place)

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}


// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      var circle = new google.maps.Circle(
          {center: geolocation, radius: position.coords.accuracy});
      autocomplete.setBounds(circle.getBounds());
    });
  }
}

views.py

class PropertyCreateView(CreateView):
    model = Property
    fields = ['address', 'postal_code', 'price',
              'details', 'sales_status', 'property_type']

    def form_valid(self, form):
        return super().form_valid(form)

detail.html

{% load crispy_forms_tags %}

      {% block content%}
      <div class="container">
        <div class="card o-hidden border-0 shadow-lg my-2">
          <div class="card-body p-0">
            <div class="row">
              <div class="col-lg-12">
                <div class="p-5">
                  <div class="text-center">
                    <h1 class="h4 text-gray-900 mb-4">New Property</h1>
                  </div>
                    <form method="POST">
                      {% csrf_token %}
                      <div class="form-group">
                        <label>Address: </label>
                          <div id="locationField">
                              <input id="autocomplete"
                                 placeholder="Enter your address"
                                 onFocus="geolocate()"
                                 type="text"
                                 name="full_address"
                              class="form-control"
                              />
                          </div>
                      </div>
                      <fieldset class="form-group">
                          {{ form|crispy }}
                      </fieldset>
                      <div class="form-group">
                          <button class="btn btn-primary btn-user btn-block"" type="submit">Add Property</button>
                      </div>
                    </form>
                  <hr>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

        {% include 'properties_app/autocomplete.html' %}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...