【问题标题】:django CSRF verification failed. Request aborteddjango CSRF 验证失败。请求中止
【发布时间】:2015-03-08 18:56:24
【问题描述】:

我在 django 项目上创建表单。我有一个错误 csrf 失败。

我的 wievs.py 文件:

def durum(request): 
    if request.method == "POST":
        adi = request.POST.get('durum')
        db = sql.connect("/usr/connect.db")
        im = db.cursor()
        db.execute("INSERT INTO durum VALUES ("+str(adi)+")")
        db.commit()
        asd = "Durum mesajı '"+str(adi)+"' olarak değiştirildi."
        return render(request, asd, {})
    else:
        BASE = os.path.dirname(os.path.abspath(__file__))
    return HttpResponse(open(os.path.join(BASE, "html/durum.html")).read())

我的 urls.py 文件:

url(r'^durum/', db.durum),

我的 html 文件:

<form action="/durum" method="post">
{% csrf_token %}
<table>
    <tr><th>Durum Mesajı:</th><td><input type="text" name="durum"/></td></tr>
     <tr><th></th><td><input type="submit" value="Ekle"/></td></tr>
</table>

【问题讨论】:

  • 首先,您应该将 action="/durum" 更改为 action="。"因为您大部分时间都会发布到相同的网址
  • 第二个你没有渲染模板,所以 csrf 令牌永远不会被创建。尝试使用 return render()
  • 如果你想使用纯 HTML 并直接执行 SQL,我完全不明白你为什么要使用 Django。
  • 因为我有 linux 服务器。我不擅长 php 或 asp
  • 那不是我的意思。你为什么不实际使用 Django 给你的功能呢?尤其是您现在对 SQL 注入完全开放:如果我将 foo;DROP TABLE durum;-- 发布到您的表单中,您的所有数据都将被删除。

标签: python django python-2.7 django-forms


【解决方案1】:

您应该使用 django 模板和 RequestContext。 检查它的非常快速的方法: 在您的应用文件夹中创建以下目录结构:

1.templates/myapp_name 使用应用名称,而不是项目名称!

  1. 创建文件 my_template.html

  2. 在您的视图中添加导入:

    从 django.shortcuts 导入渲染

添加将您的退货替换为

return render('myapp_name/my_template.html')

阅读更多关于配置模板目录: Django template Path

阅读有关渲染的更多信息: https://docs.djangoproject.com/en/1.7/intro/tutorial03/#a-shortcut-render

注意: 最好使用 django 表单而不是您的方式: https://docs.djangoproject.com/en/1.7/topics/forms/ 和基于类的视图而不是函数(相信我,它们可能看起来很复杂 - 它们真的很棒: https://docs.djangoproject.com/en/1.7/topics/class-based-views/

也尽量不要使用硬编码的网址,而是使用https://docs.djangoproject.com/en/1.7/topics/http/urls/#reverse-resolution-of-urls 它会为您完成所有工作!

【讨论】:

    【解决方案2】:

    你应该按照“django-way”来渲染你的模板。您的视图的工作方式是将模板作为纯 html 发送,而不是对其进行处理。 试试这个方法:

    def durum(request): 
    if request.method == "POST":
        adi = request.POST.get('durum')
        db = sql.connect("/usr/connect.db")
        im = db.cursor()
        db.execute("INSERT INTO durum VALUES ("+str(adi)+")")
        db.commit()
        asd = "Durum mesajı '"+str(adi)+"' olarak değiştirildi."
        return render(request, asd, {})
    else:
        return render('your_template_name.html', context_instance=RequestContext(request))
    

    这样,django 将处理您的模板并呈现正确的 csrf_token。我强烈建议您遵循 djangoproject.com 上的教程并使用 ORM

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 1970-01-01
      • 2014-02-03
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多