4

I've just changed my code from function based views to class based views and now am getting an error I can't seem to resolve.

The error appears when a user presses a button to submit their location coordinates.

Method Not Allowed: /connect/post [2019/02/11 14:27:17] HTTP POST /connect/post 405 [0.00, 127.0.0.1:57896]

Everything was working before and I can't figure out what I am doing wrong. I have both the get and post requests. Could someone point me in the right direction?

views.py

class ConnectView(View):
    template_name = 'connect/home.html'
    def get(self, request, *args, **kwargs):
        context = {
            'users': User.objects.exclude(username=request.user),
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        location = Location(latitude=request.POST['latitude'], 
longitude=request.POST['longitude'], user = request.user)
        location.save()
        return JsonResponse({'message': 'success'})

urls.py

urlpatterns = [
    path('', connect_views.ConnectView.as_view(), name='connect_home'),
]

connect.html

<script>
function showPosition(position) {
    pos = position;
    var { latitude, longitude } = pos.coords;
    $('#btn_submit').attr("disabled", null);
  }

  $(document).ready(function() {
    $demo = $("#demo");
    $('#btn_submit').on('click', function() {
      var data = pos.coords;
      data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
      $.post("post", data, function() {
        alert("Location Confirmed!");
      });
    });
  });

</script>

---omitted irrelevant code--
<button type="submit" id="btn_submit" class="btn btn-success" disabled>2. Confirm Location </button>
Trilla
  • 842
  • 7
  • 24
  • 2
    Are you sure that that is the right URL you are posting to (maybe it should be only `connect/`). Here is a [similar question](https://stackoverflow.com/a/27584421/9225671) that has some pointers to check for usual causes for this kind of error. – Ralf Feb 11 '19 at 14:42
  • Note to self: 405 errors are, most often than not, just 404 in disguise. – Sebastián Vansteenkiste Oct 30 '19 at 15:09

1 Answers1

4

You probably are posting to the wrong URL (connect/post/ instead of connect/). This question has some pointers to check for usual causes of this error.

You could try by changing this line

$.post("post", data, function() {

to

$.post(window.location, data, function() {
Ralf
  • 13,322
  • 4
  • 31
  • 55
  • Thanks very much, that was indeed the problem. What is the benefit of doing `window.location` over `$.post("", data, function() {` ? Cheers! – Trilla Feb 11 '19 at 15:13
  • @Trillz Oh, does `$.post("", ...);` work as well? I did not know that. If it does work, then of course that is less code and probably a better option then. – Ralf Feb 12 '19 at 09:17