使用get请求的django ajax post请求中缺少csrf令牌

时间:2016-09-07 12:07:14

标签: django datatables

我正在使用metronic数据表,其中我有一个ajax函数工作的文件。问题是,当我在ajax函数中使用类型“GET”它可以工作但在POST中它不起作用并且它在控制台中给出了CSRF令牌丢失错误,但是在GET的情况下它没有给出任何错误,我使用的是django框架对于我的网站和我的ajax功能是: -

"ajax": { // define ajax settings
    "url": document.URL, // ajax URL
    "type": "POST", // request type
    "timeout": 20000,
    "data": function(data) { // add request parameters before submit
        $.each(ajaxParams, function(key, value) {
            data[key] = value;
        });
        Metronic.blockUI({
            message: tableOptions.loadingMessage,
            target: tableContainer,
            overlayColor: 'none',
            cenrerY: true,
            boxed: true
        });
    },
}

urls.py文件是:

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

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^logout$', views.logout, name='logout'),
    url(r'^dashboard$', views.dashboard, name='dashboard'),
    url(r'^profile$', views.profile, name='profile'),
    url(r'^edit-profile$', views.edit_profile, name='edit-profile'),
    url(r'^check-password$', views.check_password, name='check-password'),
    url(r'^help$', views.faq_management, name='help'),
    url(r'^testing$', views.testing_database, name='testing'),
    url(r'^add-faq$', views.add_faq, name='add-faq')
]

与此功能相关的视图是:

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.exceptions import ObjectDoesNotExist
from models import Admin, Help
from django.contrib import messages
from django.utils.html import escape
from .forms import ImageUploadForm
import json
from datetime import datetime

def faq_management(request):
if 'admin_id' in request.session:
    if request.method == 'GET':
        if request.is_ajax():
            ajax_data = request.GET
            if ajax_data['length'] !=-1 :
                limit = ajax_data['length']
            else :
                limit="all"
            questions = Help.objects.all().filter().values('id','question','description','status','created','modified').order_by('-id')
            datalist = []
            i=1;
            for que in questions:
                if(que['status']=='1'):
                    checked='on'
                else:
                    checked='off'
                actionValues='<a title="Edit" class="btn btn-sm green margin-top-10" href=""> <i class="fa fa-edit"></i></a>';
                inner_data_list = [
                    i,
                    que['question'], 
                    (que['description'][:150] + '..') if len(que['description']) > 150 else que['description'],
                    '<div id=%s class="bootstrap-switch  bootstrap-switch-%s  bootstrap-switch-wrapper bootstrap-switch-animate toogle_switch"><div class="bootstrap-switch-container" ><span class="bootstrap-switch-handle-on bootstrap-switch-primary">&nbsp;Active&nbsp;&nbsp;</span><label class="bootstrap-switch-label">&nbsp;</label><span class="bootstrap-switch-handle-off bootstrap-switch-default">&nbsp;Inactive&nbsp;</span></div></div>'%(que['id'],checked),
                    que['created'],
                    que['modified'],
                    actionValues
                ]
                datalist.append(inner_data_list)
                i += 1  
            iTotalRecords=questions.count()
            iDisplayLength = int(ajax_data['length']);
            iDisplayStart = int(ajax_data['start']);
            if iDisplayLength < 0 :
                iDisplayLength = iTotalRecords
            sEcho = int(ajax_data['draw'])
            records = {}
            records['data'] = {}
            records['data'] = {}
            records['data'] = datalist
            records['customActionStatus'] = {}
            records['customActionMessage'] = {}
            records['draw'] = {}
            records['recordsTotal'] = {}
            records['recordsFiltered'] = {}
            if request.GET.get('customActionType', '') == 'group_action':
                records['customActionStatus'] = 'OK'
                records['customActionMessage'] = 'Group action successfully has been completed. Well done!'
            records["draw"] = sEcho
            records["recordsTotal"] = iTotalRecords
            records["recordsFiltered"] = iTotalRecords
            return HttpResponse(json.dumps(records, default=json_serial))

        admin = Admin.objects.get(pk = request.session["admin_id"])
        return render(request, 'admin/faq-manage.py', {
            'adminInfo': admin,
        })
else:
    messages.add_message(request, messages.ERROR, 'ERROR! Kindly login first.')
    return redirect(index)  

1 个答案:

答案 0 :(得分:1)

您不会因GET而收到错误,因为只有POST次请求才需要CSRF令牌。

在文档中查看此主题 - https://docs.djangoproject.com/en/dev/ref/csrf/

相关问题