【问题标题】:Method Not Allowed (POST) Django 405 error方法不允许 (POST) Django 405 错误
【发布时间】:2019-07-05 02:06:32
【问题描述】:

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

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

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/)。这是一个similar question,它有一些指针可以检查这种错误的常见原因。
  • 自我注意:405 错误通常只是伪装的 404。

标签: python django django-views http-status-code-405


【解决方案1】:

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

你可以换行试试

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

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

【讨论】:

  • 非常感谢,确实是这个问题。做 window.location$.post("", data, function() { 有什么好处?干杯!
  • @Trillz 哦,$.post("", ...); 也有效吗?我不知道。如果它确实有效,那么这当然是更少的代码并且可能是一个更好的选择。
猜你喜欢
  • 2013-12-05
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2021-09-17
  • 2014-05-23
  • 2012-08-24
  • 2018-02-16
相关资源
最近更新 更多