search
HomeWeb Front-endJS TutorialHow to use the ajax post method in the Django framework

Django is an open source web application framework, written in Python. This article introduces how the Django framework uses the ajax post method. Interested friends should come and learn together.

Django is an open source web application framework. Source code web application framework, written in Python. The MVC software design pattern is adopted, namely model M, view V and controller C. It was originally developed to manage some of the news content-based websites of Lawrence Publishing Group, that is, CMS (Content Management System) software. And was released under the BSD license in July 2005. This frame is named after the Belgian gypsy jazz guitarist Django Reinhardt.

Today I found a problem when trying to call jQuery's ajax. The server can return normally using the GET method, but not the POST method. Later, testing the form-based POST method also didn't work. As long as POST will report HTTP 403 error! very strange. . .

After searching a lot of information on the Internet, it turns out that it is due to a problem with Django's Cross Site Request Forgery protection mechanism. This mechanism is to protect against CSRF attacks. What is a crsf attack? Taolin blog has a relatively simple explanation. Solution Django's official website has provided http://docs.djangoproject.com/en/dev/ref/contrib/csrf/. After modification according to the instructions, ajax can be posted smoothly.

The specific method is to first solve the POST of the form. Find MIDDLEWARE_CLASSES in the settings.py file and add a middleware: 'django.middleware.csrf.CsrfViewMiddleware'. The modified code is as follows:

Python code

MIDDLEWARE_CLASSES = ( 
 'django.middleware.common.CommonMiddleware', 
 'django.contrib.sessions.middleware.SessionMiddleware', 
 'django.middleware.csrf.CsrfViewMiddleware', 
 'django.contrib.auth.middleware.AuthenticationMiddleware', 
 'django.contrib.messages.middleware.MessageMiddleware', 
 'django.middleware.csrf.CsrfResponseMiddleware', #加入这个中间件 
)


After this modification, the problem of HTTP 403 submission via form POST can be solved. Just changing the Post submission of ajax in this way is not enough. You also need to hook up a cookie processing process for each submission. That is, every time you submit, this process is triggered and the csrf token is added to the submitted http header. Fortunately, if you use jQuery to handle ajax, Django directly sends a piece of code to solve the problem. Put it in a separate js file and introduce it in the html page. Note that this js file must be imported after the jquery js file is imported. I copied the code directly, as follows:

Js code

##

$('html').ajaxSend(function(event, xhr, settings) { 
 function getCookie(name) { 
  var cookieValue = null; 
  if (document.cookie && document.cookie != '') { 
   var cookies = document.cookie.split(';'); 
   for (var i = 0; i < cookies.length; i++) { 
    var cookie = jQuery.trim(cookies[i]); 
    // Does this cookie string begin with the name we want? 
    if (cookie.substring(0, name.length + 1) == (name + &#39;=&#39;)) { 
     cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
     break; 
    } 
   } 
  } 
  return cookieValue; 
 } 
 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { 
  // Only send the token to relative URLs i.e. locally. 
  xhr.setRequestHeader("X-CSRFToken", getCookie(&#39;csrftoken&#39;)); 
 } 
});

After this After a lot of trouble, I can finally use ajax to communicate with Django normally.

Usage of ajax in Django

The front-end ajax code is as follows:

$.ajax({
 type:&#39;GET&#39;,
 url:&#39;/store/ds_mgmt_wx/ajax_handle&#39;,
 dataType:&#39;html&#39;,
 success:function(data)
  {
   alert(data);
  },
 error:function(data)
 {
  alert(data); 
 }
});

The return method of the corresponding code on the backend is as follows:

if act_job == &#39;ajax_handle&#39;:
  return HttpResponse(&#39;ajax_handle&#39;)

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed explanation of ajax jtemplate to implement dynamic paging

A simple implementation of Ajax showing progress during the request process

JQuery Ajax dynamically generates Table

##

The above is the detailed content of How to use the ajax post method in the Django framework. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)