【问题标题】:Forbidden (403) CSRF verification failed. Request aborted when I hit the submit button禁止 (403) CSRF 验证失败。当我点击提交按钮时请求中止
【发布时间】:2015-07-31 02:18:27
【问题描述】:

我正在处理 django 身份验证请求,但我收到了禁止的错误,我检查了我的代码,但似乎没有错误。

HTML

    <div class="grad"></div>
    <div class="header">
    <div>MLAT<span>SI</span></div>
    </div>
    <form action="{{views.login_user}}" method="POST">{% csrf_token %}
    <div class="login">
    <img src="{% static "img/Airplane.png" %}">
    <div id="h" class="home">
    <input type="text" placeholder="Login" name="username" value="">
    <input type="password" placeholder="Mot de passe" name="password" value="">
    <input style="float: left; width: 173px" type="submit" value="Log in" > 
    <input formaction="/form_registration.html/" style="float: right; width: 173px" type="submit" value="Register">

views.py

def login_user(request):
    username = request.POST.get("username")
    password = request.POST.get("password")
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        return HttpResponse("You're logged in.")
    else:
        return HttpResponse("Your username and password didn't match.")

【问题讨论】:

  • 显示你渲染html页面的方法。
  • {{views.login_user}} 是否输出您期望的结果?我也很好奇你为什么不止一次定义表单的action...
  • 您是否更改了任何默认的 CSRF_* 设置?
  • csrf-token 是否渲染到模板中?您是否启用了 cookie?
  • 你能发布错误回溯吗?

标签: python html django


【解决方案1】:

您的导入包似乎有问题。而且您调用视图的方式不正确,您应该仔细阅读 Django 文档

【讨论】:

    【解决方案2】:

    看起来像重复:Django - {% csrf_token %} was used in a template, but the context did not provide the value

    基本上,您的 login_user 视图没有使用任何渲染/上下文,因此会出现错误(我不知道这是否与调用登录 url 时调用的视图相同)。所以 Django 看到 csrf_token 但从不将其转换为实际的令牌值。

    from django.shortcuts import render
    

    但实际上,您的表单和视图看起来都非常错误。表单操作 {{ views.login_user }} 不正确。你不能这样称呼视图。您的注册按钮转到看起来像 HTML 页面的地方。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 2017-08-06
      • 2018-11-05
      • 2018-06-06
      • 2017-06-26
      • 2019-07-22
      • 2020-05-04
      相关资源
      最近更新 更多