方法不允许 (POST) Django 405 错误

Method Not Allowed (POST) Django 405 error

我刚刚将我的代码从基于函数的视图更改为基于 class 的视图,现在我遇到了一个我似乎无法解决的错误。

当用户按下按钮提交他们的位置坐标时出现错误。

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

之前一切正常,但我不知道自己做错了什么。我有两个 get and post 请求。有人能给我指出正确的方向吗?

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>

您可能发布到错误的 URL(connect/post/ 而不是 connect/)。 This question 有一些指示可用于检查此错误的常见原因。

您可以尝试更改此行

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

$.post(window.location, data, function() {