禁止(403)CSRF验证失败。请求中止

时间:2016-05-02 11:02:09

标签: python django

我正在尝试将表单中的数据发布到名为insert_data的url中。表单发布的数据应插入数据库。填写表单后,当我单击提交按钮给出错误。我在表单中包含了{%csrf_token%}。我提到了很多关于这个错误的解决方案,这无济于事。

Forbidden (403)
CSRF verification failed. Request aborted.

urls.py:

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^chain$', views.chain, name='chain'),
    url(r'^add$', views.add, name='add'),
    url(r'^insert_order$', views.insert_order, name='insert_order'),
]

views.py

from django.shortcuts import render, render_to_response
from .models import Customers
from django.db import connection

def add(request):
    cursor = connection.cursor()
    cursor.execute('''select polls_products.modelNumber, polls_products.description, polls_products.cost from polls_products;''')
    results = cursor.fetchall()
    x = cursor.description
        resultsList = []   
        for r in results:
            i = 0
            d = {}
            while i < len(x):
                d[x[i][0]] = r[i]
                i = i+1
            resultsList.append(d)

    cursor1 = connection.cursor()
    cursor1.execute('''select polls_employees.first_name, polls_employees.last_name from polls_employees;''')
    results1 = cursor1.fetchall()
    x = cursor1.description
        resultsList1 = []   
        for r in results1:
            i = 0
            d = {}
            while i < len(x):
                d[x[i][0]] = r[i]
                i = i+1
            resultsList1.append(d)
    return render_to_response('polls/add.html', {"results1":resultsList1, "results":resultsList})

def insert_order(request):
    print "came"
    if request.method == "POST":
            print request.POST['product']
            print request.POST['emp']

        return render(request, 'polls/index.html', {})

add.html

<h1>Add Orders</h1>

<form action="{% url 'insert_order' %}" method="POST">
    {% csrf_token %}
Product: <select name="product">
<option disabled="disabled" selected="selected">select product</option>
    {% for r in results %}

            <option value="{{r.key}}" >{{r.modelNumber}} {{r.description}} {{r.cost}}</option>

    {% endfor %}
</select>
<br/><br/>
Employee: <select name="emp">
<option disabled="disabled" selected="selected">select Employee</option>
{% for r in results1 %}
     <option value="{{r.key}}" >{{r.first_name}} {{r.last_name}} </option>
{% endfor %}
</select>
<br/><br/>
<h3>Customer Details</h3>
First Name: <input type="text" id="fname" name="fname">
<br/><br/>
last Name: <input type="text" id="fname" name="fname">
<br/><br/>
City: <input type="text" id="fname" name="fname">
<br/><br/>
State: <input type="text" id="fname" name="fname">
<br/><br/>
Phone No: <input type="text" id="fname" name="fname">
<br/><br/>
<input type="submit" value="Save Order">
</form>

请帮忙。我真的陷入了困境。

2 个答案:

答案 0 :(得分:0)

每次使用RequestContext(request)

时,您都必须使用renter_to_response

return render_to_response("login.html", {"registration_id":registration_id}, context_instance=RequestContext(request))

您必须导入身份验证并登录:

from django.contrib.auth import authenticate, login

在设置更新

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
MIDDLEWARE_CLASSES = [
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

请参考 https://docs.djangoproject.com/ja/1.9/ref/csrf/

答案 1 :(得分:0)

如果您没有在您的应用中使用用户身份验证,请尝试使用django装饰器(function () { var dropdownMenu; $(window).on('show.bs.dropdown', function (e) { dropdownMenu = $(e.target).find('.dropdown-menu'); $('body').append(dropdownMenu.detach()); var eOffset = $(e.target).offset(); dropdownMenu.css({ 'display': 'block', 'top': eOffset.top + $(e.target).outerHeight(), 'left': eOffset.left }); }); $(window).on('hide.bs.dropdown', function (e) { $(e.target).append(dropdownMenu.detach()); dropdownMenu.hide(); }); })(); function dataFormater(value, row, index) { var id = row.id; var strHTML = "<div class='btn-group' astyle='position: absolute'><button type='button' class='btn btn-primary btn-xs dropdown-toggle' data-toggle='dropdown'>Options<span class='caret'></span></button><ul class='dropdown-menu text-left' role='menu' style='position:absolute'>"; strHTML += "<li><a href='/Edit/" + id + "'><span class='glyphicon glyphicon-edit'></span>&nbsp;&nbsp;Edit</a></li>"; strHTML += "<li><a href='/Delete/" + id + "'><span class='glyphicon glyphicon-remove'></span>&nbsp;&nbsp;Remove</a></li>"; strHTML += "</ul></div>"; var valReturn = strHTML; return valReturn; }

前:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.css">
<script src="https://rawgit.com/wenzhixin/bootstrap-table/master/src/bootstrap-table.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<table id="table" data-classes="table table-hover table-condensed" data-toggle="table" data-show-columns="true" data-height="250">
    <thead>
        <tr>
            <th data-field="id">Item ID</th>
            <th data-field="name">Item Name</th>
            <th data-field="price">Item Price</th>
            <th data-formatter="dataFormater" data-width="90">-</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Item 1</td>
            <td>$1</td>
            <td></td>
        </tr>
        <tr>
            <td>2</td>
            <td>Item 2</td>
            <td>$2</td>
            <td></td>
        </tr>
        <tr>
            <td>3</td>
            <td>Item 3</td>
            <td>$3</td>
            <td></td>
        </tr>
    </tbody>
</table>