Django视图不接受来自html的POST

时间:2018-02-01 21:23:21

标签: python django python-3.x

我正在创建一个登录视图,但是我收到一条错误,指出不允许使用POST方法。

这是视图类:

class LogIn(View);
    def get(self, request):

        if request.method == 'POST':
            username = request.POST.get('email')
            password = request.POST.get('password')

            user = authenticate(username=username, password=password)

            if user:
                if user.is_active:
                    login(request, user)

                    return HttpResponseRedirect(reverse('control_center'))
                else:
                    return HttpResponse('Account not active!')
            else:
                return HttpResponse('Invalid user/name!')
        else:
            return render(request, 'UserManagerApp/login.html', {})

这是html表格:

<form action="{% url 'UserManagerApp:login' %}" method="post">
    {% csrf_token %}
    <div class="card-body">
      <label for="email">Email address</label>
      <input type="email" class="form-control" name="email" placeholder="example@attractora.com">
      <label for="password" style="padding-top: 10px">Password</label>
      <input type="password" class="form-control" name="password">
    </div>
    <div class="card-footer text-center">
      <button type="submit" class="btn btn-primary" value="Login">Accept</button>
      <button type="cancel" class="btn btn-danger">Cancel</button>
    </div>
  </form>

这是我得到的错误:

[01/Feb/2018 21:00:45] "GET /user_manager/login/ HTTP/1.1" 200 1686
Method Not Allowed (POST): /user_manager/login/
[01/Feb/2018 21:11:25] "POST /user_manager/login/ HTTP/1.1" 405 0

我正在关注一些在线指示,但显然,我在某个时候跨过了。

2 个答案:

答案 0 :(得分:1)

您需要在LogIn类中定义一个名为post()的单独函数。您只定义了get()方法,该方法仅处理GET个请求。

有关详细信息,请参阅Django documentation on class-based views

答案 1 :(得分:0)

def get(self, request):

永远不会使用request.method == 'POST'调用具有此名称的方法; def post(...)为此。