Django Views Unleashed Part 2 ( get_full_path_info,get_host,get_port,is_ajax)

||
Posted 1 year, 6 months ago
||
Views 173
||
2 min read
0 reactions

Sometime, we may need to explore some of the below moethods & objects from Django out of the box for various reason,

Request Methods & Objects   Values
get_full_path_info GET current URL path
get_host GET current HOST request
is_ajax It return TRUE/FALSE based on AJAX request from JS file/HTML
body  Sometime we will pass the data as byte 

Above method is used for various situations,

For example,

Add the below script in base.html 

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>
    <form id="form-test">
    {% csrf_token %}
        <input type="text">
        <button id="test"  type="submit">Submit</button>
    </form>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
   <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script>

 const ajaxTestEl = document.getElementById("form-test")
 ajaxTestEl.addEventListener("submit", handleFormSubmit)

 function handleFormSubmit(event){
    event.preventDefault()

    const myForm = event.target
    const myFormData = new FormData(myForm)
    console.log(myFormData)

    const url = '/1/'
    const method  = 'POST'

    const xhr = new XMLHttpRequest();
 
    xhr.open(method, url)
    xhr.setRequestHeader("HTTP_X_REQUESTED_WITH","XMLHttpRequest")
    xhr.setRequestHeader("X-Requested-With","XMLHttpRequest")
    xhr.onload = function(){
        console.log('Success')

        
    }
    xhr.onerror = function(){
        console.log('Failed')
    }
    xhr.send(myFormData)
}

</script>


  </body>
</html>

In order to get the POST data from AJAX request , we have to use request.body objects instead request.POST['name']

Now, we can use below options to get the AJAX byte data in view.

from django.shortcuts import render,redirect
from django.http import HttpResponse,HttpResponseNotFound, JsonResponse
import json

def index(request, *args, **kwargs):
    # body_unicode = request.body.decode('utf-8')
    # body = json.loads(body_unicode)
    # print(body['test'])
   
    if request.method == 'POST':
        print(request.body)
        print(request.POST['test'])
        body_unicode = request.body.decode('utf-8')
        print(body_unicode)
        # body = json.loads(body_unicode)
        # print(body)
        return JsonResponse({})
        
    # print(dir(request))
    # print(request.body)
    # return HttpResponseNotFound('<h1>Page not found</h1>')

    return render(request, 'tutorial/base.html', {} )

So, based on data POST from html page, we could use our request METHOD accordingly.

Another intereting one is View decorator for accepting methods,

from django.views.decorators.http import require_http_methods
@require_http_methods(["GET","POST"])
def index(request, *args, **kwargs):
    # body_unicode = request.body.decode('utf-8')
    # body = json.loads(body_unicode)
    # print(body['test'])
   
    if request.method == 'POST':
        print(request.body)
        print(request.POST['test'])
        body_unicode = request.body.decode('utf-8')
        print(body_unicode)
        # body = json.loads(body_unicode)
        # print(body)
        return JsonResponse({})
        
    # print(dir(request))
    # print(request.body)
    # return HttpResponseNotFound('<h1>Page not found</h1>')

    return render(request, 'tutorial/base.html', {} )

Happy Coding !!!


0 reactions

Discussion


Actively looking for JOBS
Joined on April 15, 2020


Latest Videos


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message