How Django Realize PUT and DELETE Simple and Quick

  • 2021-07-26 08:33:29
  • OfStack

All the friends who use django should know that we can't handle PUT and DELETE happily


$.ajax({
  url: 'XXX',
  type: 'PUT',
  dataType: 'json',
  data: {
    's': $("#select-id").find("option:selected").text()
  },
  success: function (data) {
    console.log('ok');
  }
})

def func(request):
  if request.method == 'GET':
    s = request.GET.get('s', None)
    return XXX
  elif request.method == 'POST':
    s = request.POST.get('s', None)
    return XXX
  elif request.method == 'PUT':
    s = request.PUT.get('s', None)          #  We hope that the pleasant acquisition will continue to be processed 
    return XXX
  elif request.method == 'DELETE':
    s = request.DELETE.get('s', None)        #  We hope that the pleasant acquisition will continue to be processed 
    return XXX
  else:
    pass

Unfortunately, by default, we can't easily write url based on restful, but the power of lazy cancer is infinite! The witty little north uses middleware to achieve this goal by consulting materials and customizing modifications

First of all, we need to add a middleware py file under an app in django, and name it at will. Here my name is middleware


#!/usr/bin/env python
# -*- coding:utf8 -*-
# __author__ = ' Beirum Q'

from django.http import QueryDict
try:
  from django.utils.deprecation import MiddlewareMixin  # 1.10.x
except ImportError:
  MiddlewareMixin = object                # 1.4.x-1.9.x


class HttpPost2HttpOtherMiddleware(MiddlewareMixin):
  def process_request(self, request):
    """
     You can continue to add HEAD , PATCH , OPTIONS And custom methods 
    HTTP_X_METHODOVERRIDE Looks like a previous version key ? ? ? 
    :param request:  Requests processed by native middleware 
    :return:
    """
    try:
      http_method = request.META['REQUEST_METHOD']
      if http_method.upper() not in ('GET', 'POST'):
        setattr(request, http_method.upper(), QueryDict(request.body))
    # except KeyError:
    #   http_method = request.META['HTTP_X_METHODOVERRIDE']
    #   if http_method.upper() not in ('GET', 'POST'):
    #     setattr(request, http_method.upper(), QueryDict(request.body))
    except Exception:
      pass
    finally:
      return None

Then register this middleware in settings of django


MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'yourappname.middleware.HttpPost2HttpOtherMiddleware',              #  Change to your own app Name Oh 
]

Related articles: