Post user geolocation to Django class based view

193 views Asked by At

I am trying to post user geolocation to Django class based view. Apparently, javascript is not so friendly to me. How can I post user geolocation to UserProfileView class based view in django, ajax?

<body>

<div>
   <div>
    <strong>Current Position: </strong> {{ profile.user_location }}<br/>
    </div>

<label for="locations-status">Enable Location?</label>
<input type="checkbox" id="locations-status">
<form id="location_form" method="POST" action="{% url 'rent_app:add-location' %}">
    {% csrf_token %}
 <button type="button" id="send-my-url-to-django-button">Send URL to Django View</button>
</form>
{% block js %}
<script>
      function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }

      $.ajaxSetup({
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
          }
        }
      });

      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
          function (position) {
            console.log('Position has been set successfully');
            console.log(position.coords);
          
         dataToSend = {
              "permission": $("input[name=locations-status]").is(':checked'),
              "user_location": position,
            };
          });
      }
        
          
$("#send-my-url-to-django-button").click(function() {
            $.ajax({
              type: "POST",
              dataType: 'json',
              url: "{% url 'rent_app:add-location' %}",
              data: JSON.stringify(dataToSend),
              success: function (msg) {
                console.log('Succeeded!');            
              },
              error: function (err) {
                console.log('Error!');
              }
            });
          }, function (error) {
              console.log('Position could not be obtained.');
          }
        );
</script>
{% endblock %}
</body>

views.py:

class UserProfileView(View):
    form_class = UserProfileModelForm
    template_name = "user_profile.html"

    def get(self, *args, **kwargs):
        form = self.form_class()
        user_locations = UserProfile.objects.user_location()
        return render(self.request, self.template_name, 
            {"form": form, "user_location": user_locations})

    def post(self, *args, **kwargs):
        if self.request.is_ajax and self.request.method == "POST":
            form = self.form_class(self.request.POST)
            if form.is_valid():
                instance = form.save()
                ser_instance = serializers.serialize('json', [ instance, ])
                # send to client side.
                return JsonResponse({"instance": ser_instance}, status=200)
            else:
                return JsonResponse({"error": form.errors}, status=400)

        return JsonResponse({"error": ""}, status=400)
2

There are 2 answers

7
Dimitar On

The context is {"form": form, "user_location": user_locations}) you don't have any profile passed in the context. I think you need to use {{ user_location }} instead of {{ profile.user_location }}

0
Kaleab Woldemariam On

Just make the javascript work. Thank you, that would be helpful.