Python Easyui + django--Integrated CSRF Protection Remover

Source: Internet
Author: User
Tags sqlite

First, a complete picture:

about Django CSRF middleware protection GET is not done csrf verified but post default authentication $.cookie (' Csrftoken ')) "value"

The first approach: removing middleware from the main configuration file settings.py

The second type: No need to unregister the first method #' Django.middleware.csrf.CsrfViewMiddleware ',

     Introduced from   DJANGO.VIEWS.DECORATORS.CSRF import csrf_exempt in views.py  , Csrf_protect

                                      Add @csrf_exempt before required method   do not enable CSRF               


The third type: verify Form form by CSRF add {% Csrf_token%}

Ajax is verified by CSRF:
                 $.ajax ({    '/remove/',    ' POST ',    data: {id:row.id},    headers: { ' X-csrftoken ': $.cookie (' Csrftoken ')},  

define global AJAX headers request Header CSRF validation

        $ (function () {            $.ajaxsettings ({                beforesend:function () {xhr,settings) {                    Xhr.setrequestheader (' X-csrftoken ', $.cookie (' Csrftoken ')})}        );

  

Models table Structure Code

From django.db import models# generate table structure based on class object #python manage.py makemigrations# generate corresponding database table based on table structure Sqlite#python manage.py Migrateclass person (models. Model):    uesr_name = models. Charfield (max_length=32)    user_sex = models. Charfield (max_length=32, null=true,blank=true)    user_phone=models. Integerfield (max_length=255, null=true,blank=true)    user_addre=models. Charfield (max_length=32, Null=true,blank=true)

  

urls.py URL Code

 fromdjango.conf.urls Import URL fromdjango.contrib Import Admin fromApp.views Import *Urlpatterns=[url (r'^admin/', admin.site.urls), url (r'^$', Indexl), url (r'^start/', App_start), url (r'^read/', read_all_sql), url (r'^edit/(? p<id>\d+)', edit_usernmae), url (r'^remove/', remove_us_id),]

App.views views Code

#-*-Coding:utf-8-*-from django.views.decorators.csrf import csrf_exempt, csrf_protectfrom django.shortcuts Import ren  Der, HttpResponse, Httpresponseredirectimport models, Jsonimport sysreload (SYS) # Create your views here. #indexl &def INDEXL (Request): Return Httpresponseredirect ("http://127.0.0.1:8000/start/") #Read all SQLite data@csrf_exemptdef Read_all_sql (Request): Obj_all=models. Person.objects.all () ealist=[] for Li in Obj_all:eaList.append ({"FirstName": Li. Uesr_name, "LastName": Li. User_sex, "phone": Li. User_phone, "email": li.    User_addre, "id": li.id}) Ealist_len=json.dumps (Len (ealist)) Json_data_list = {' Rows ': ealist, ' Total ': Ealist_len} Easylist=json.dumps (json_data_list) return HttpResponse (easylist) #Edit_UserName @csrf_exemptdef Edit_usernmae ( Request,id): print (ID) print (request.method) if Request.method = = ' POST ': uesr_name=request. Post.get (' FirstName ') user_sex=request. Post.get (' LastName ') user_phone=Request. Post.get (' phone ') user_addre=request. Post.get (' email ') dic={' uesr_name ': uesr_name, ' user_sex ': user_sex, ' user_phone ': User_phone, ' User_ad '        Dre ': User_addre}; Models.  Person.objects.filter (id=id). Update (**dic) return HttpResponse ("EDIT_OK") #add user_name + start_appdef App_start (Request): # Add_save_user if request.method== "POST": Print ("POST") print (request. POST) uesr_name=request. Post.get (' FirstName ') user_sex=request. Post.get (' LastName ') user_phone=request. Post.get (' phone ') user_addre=request. Post.get (' email ') dic={' uesr_name ': uesr_name, ' user_sex ': user_sex, ' user_phone ': User_phone, ' User_ad '        Dre ': User_addre}; Models.    Person.objects.create (**dic) return HttpResponse ("Save") Else:print ("is null_!") return render (Request, ' app/index_bak.html ') #Remove sql_id@csrf_exemptdef remove_us_id (Request): if request.method==     "POST":   Print ("REMOVE POST") print (request. Post.get (' id ')) us_id=request. Post.get (' ID ') models. Person.objects.filter (id=us_id). Delete () return HttpResponse ("REMOVE")

  

Templates.app.index.html Code HTML code

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title>easyui Frame </title>
{% load staticfiles%}
<link rel= "stylesheet" type= "Text/css" href= "/static/jquery/themes/default/easyui.css" >
<link rel= "stylesheet" type= "Text/css" href= "/static/jquery/themes/icon.css" >
<link rel= "stylesheet" type= "Text/css" href= "/static/jquery/themes/color.css" >
<link rel= "stylesheet" type= "Text/css" href= "/static/jquery/demo/demo.css" >
<script type= "Text/javascript" src= "/static/jquery/jquery.min.js" ></script>
<script type= "Text/javascript" src= "/static/jquery/jquery.easyui.min.js" ></script>
<body>
<p>qq_237356573 (Increase and deletion) </p>

<table id= "DG" title= "My Users" class= "Easyui-datagrid" style= "width:700px;height:250px"
Url= "/read/"
Toolbar= "#toolbar" pagination= "true"
Rownumbers= "true" fitcolumns= "true" singleselect= "true" >
<thead>
<tr>
<th field= "FirstName" width= ">Name</th>"
<th field= "LastName" Width= ">SEX</th>"
<th field= "Phone" width= ">Phone</th>"
<th field= "Email" width= ">OWE</th>"
</tr>
</thead>
</table>
<div id= "Toolbar" >
<a href= "javascript:void (0)" class= "Easyui-linkbutton" iconcls= "Icon-add" plain= "true" onclick= "NewUser ()" > New user</a>
<a href= "javascript:void (0)" class= "Easyui-linkbutton" iconcls= "Icon-edit" plain= "true" onclick= "EditUser ()" > Edit user</a>
<a href= "javascript:void (0)" class= "Easyui-linkbutton" iconcls= "Icon-remove" plain= "true" onclick= "DestroyUser () ">remove user</a>
</div>

<div id= "Dlg" class= "Easyui-dialog" style= "width:400px"
Closed= "true" buttons= "#dlg-buttons" >
<form id= "FM" method= "POST" Novalidate style= "margin:0;padding:20px 50px" >
<div style= "margin-bottom:20px;font-size:14px;border-bottom:1px solid #ccc" >add user_name</div>
<div style= "margin-bottom:10px" >
<input name= "FirstName" class= "Easyui-textbox" required= "true" label= "Name:" style= "width:100%" >
</div>
<div style= "margin-bottom:10px" >
<input name= "LastName" class= "Easyui-textbox" required= "true" label= "Sex:" style= "width:100%" >
</div>
<div style= "margin-bottom:10px" >
<input name= "Phone" class= "Easyui-textbox" required= "true" label= "Phone:" style= "width:100%" >
</div>
<div style= "margin-bottom:10px" >
<input name= "Email" class= "Easyui-textbox" required= "true" label= "OWE:" style= "width:100%" >
</div>
</form>
</div>
<div id= "Dlg-buttons" >
<a href= "javascript:void (0)" class= "Easyui-linkbutton c6" iconcls= "Icon-ok" onclick= "Saveuser ()" style= "width : 90px ">Save</a>
<a href= "javascript:void (0)" class= "Easyui-linkbutton" iconcls= "Icon-cancel" onclick= "javascript:$ (' #dlg '). dialog (' Close ') "style=" width:90px ">Cancel</a>
</div>
<script type= "Text/javascript" >
Set AJAX Global Header request Header $.cookie (' Csrftoken ')
$ (function () {
$.ajaxsettings ({
Beforesend:function (xhr,settings) {
Xhr.setrequestheader (' X-csrftoken ', $.cookie (' Csrftoken '))
}
})
});


var URL;
Show edit box
function NewUser () {
$ (' #dlg '). Dialog (' Open '). Dialog (' Center '). Dialog (' Create ', ' New User ');
$ (' #fm '). Form (' clear ');
url = '/start/';
}

Edit USER
function Edituser () {
var row = $ (' #dg '). DataGrid (' getselected ');
if (row) {
$ (' #dlg '). Dialog (' Open '). Dialog (' Center '). Dialog (' Settitle ', ' Edit User ');
$ (' #fm '). Form (' Load ', row);
Ajax edit user and save to back-end SQL via Ajax
url = '/edit/' +row.id;
}
}

Create--user and save
function Saveuser () {
$ (' #fm '). Form (' Submit ', {
Url:url,
Onsubmit:function () {
return $ (this). Form (' Validate ');
},
Success:function (Result) {
if (result== "save") {
$ (' #dlg '). Dialog (' Close ');
$ (' #dg '). DataGrid (' reload ');
}else
if (result.errormsg) {
$.messager.show ({
Title: ' Error ',
Msg:result.errorMsg
});
} else {
$ (' #dlg '). Dialog (' Close '); Close the dialog
$ (' #dg '). DataGrid (' reload '); Reload the user data
}
}
});
}

Delete user based on ID
function Destroyuser () {
var row = $ (' #dg '). DataGrid (' getselected ');
if (row) {
$.messager.confirm (' Confirm ', ' is sure you want to destroy this user? ', function (r) {
if (r) {
$.ajax ({
URL: '/remove/',
Type: ' POST ',
Data: {id:row.id},
Headers: {' X-csrftoken ': $.cookie (' Csrftoken ')},
Success:function (data) {
if (data== "REMOVE") {
$ (' #dg '). DataGrid (' reload '); Reload the user data
}
},
Error:function (data) {
Alert ("Error")
}
});
}
});
}
}
</script>
</body>

  

New_user

Edit_user

Remove_user

Source: HTTPS://PAN.BAIDU.COM/S/1C25JBWC

Python Easyui + django--Integrated CSRF Protection Remover

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.