Skip to content

Instantly share code, notes, and snippets.

@solanoize
Last active July 21, 2016 10:54
Show Gist options
  • Select an option

  • Save solanoize/f8fe362ab91cc481054a334e985c297f to your computer and use it in GitHub Desktop.

Select an option

Save solanoize/f8fe362ab91cc481054a334e985c297f to your computer and use it in GitHub Desktop.
testing ajax in admin Django (1.8.6)

struktur proyek dan aplikasi

PROJECT ROOT
|
│   db.sqlite3
│   manage.py
│
├───blotik_app
│   │   admin.py
│   │   forms.py
│   │   models.py
│   │   tests.py
│   │   urls.py
│   │   views.py
│   │   __init__.py
│   │
│   ├───migrations
│   │       0001_initial.py
│   │       __init__.py
│   │
│   ├───static
│   │   │   jquery.min.js
│   │   │
│   │   ├───css
│   │   │       bootstrap-theme.css
│   │   │       bootstrap-theme.css.map
│   │   │       bootstrap-theme.min.css
│   │   │       bootstrap-theme.min.css.map
│   │   │       bootstrap.css
│   │   │       bootstrap.css.map
│   │   │       bootstrap.min.css
│   │   │       bootstrap.min.css.map
│   │   │       custom.admin.css
│   │   │
│   │   ├───fonts
│   │   │       glyphicons-halflings-regular.eot
│   │   │       glyphicons-halflings-regular.svg
│   │   │       glyphicons-halflings-regular.ttf
│   │   │       glyphicons-halflings-regular.woff
│   │   │       glyphicons-halflings-regular.woff2
│   │   │
│   │   └───js
│   │           bootstrap.js
│   │           bootstrap.min.js
│   │           custom.admin.js
│   │           main.ajax.django.js
│   │           npm.js
│   │
│   └───templates
│       ├───admin
│       │   └───blotik_app
│       │           change_form.html
│       │
│       └───blotik_app
│           │   base.html
│           │   navbar.html
│           │   pagination.html
│           │   section.html
│           │
│           └───posting
│                   detil.html
│                   index.html
│                   kirim.html
│   
│
└───blotik_project
        settings.py
        urls.py
        wsgi.py
        __init__.py
    

main.ajax.django.js

// menggunakan jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            // jQuery.trim(cookies[i]) tidak bekerja
            var cookie = cookies[i].trim(); 
            // Apakah Cookie string ini dimulai dengan nama yang kita inginkan ?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}


(function($) {
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // metode HTTP ini tidak memerlukan protection CSRF
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

})(django.jQuery);

custom.admin.js

(function($) {
    // < start of closure
    // within this block, $ = django.jQuery
    $(document).ready(function() {

        // ketika link ber-id ajax di klik
        $("#ajax").click(function(e) {
        
            // Prevent default submit.
            e.preventDefault();
        
            // prepare csrf token
            var csrftoken = getCookie('csrftoken');
        
        
            // kumpulkan data dari field
         	var judul = $('#id_judul').val();
        	var slug = $('#id_slug').val();
        	var penulis = $('#id_penulis').val();
        	var isi = $("#id_isi").val();
        
            // pengiriman data 
            $.ajax({
                // seharusnya pada url:
                // url: window.location.href, 
                // ini merupakan endpoint, umumnya urlnya sama untuk post data
                url :  "http://127.0.0.1:8000/blotik/rest/", 
                type : "POST", // http method
                data : { csrfmiddlewaretoken : csrftoken, 
                judul : judul,
                slug : slug,
                penulis: penulis,
                   isi: isi,
            }, // data dikirim dengan request post
        
                // menangani response yang sukses
                success : function(json) {
                    // sanity check lain
                    console.log(json);
             	    // contoh validasi sederhana untuk testing doang !
             	    if (json['status'] === "ok") {
             		    $("#id_judul").css("background-color", "red");
                    } else {
             		    $("#id_judul").css("background-color", "white");
             	    }
                },
        
                // menangani response saat ajax gagal
                error : function(xhr,errmsg,err) {
                    console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
                    alert("Faild !");
                }
            }); // end $.ajax
        }); // end  $("#ajax").click ...
    }); // end document ready
})(django.jQuery);

change_form.html (extends with admin template)

{% extends "admin/change_form.html" %}
{% load i18n admin_urls %}
{% block object-tools-items %}
    <li>
        <a href="{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}" class="historylink">{% trans "History" %}</a>
    </li>
    <li>
        <a href="#" id="ajax">My Link</a>
    </li>
    {% if has_absolute_url %}
        <li>
            <a href="{% url 'admin:view_on_site' content_type_id original.pk %}" class="viewsitelink">{% trans "View on site" %}</a>
        </li>
    {% endif %}
{% endblock %}

admin.py

from django.contrib import admin
from .models import Posting

class AdminPosting(admin.ModelAdmin):
    # ...
	class Media:
		css = {
			"all": ("css/custom.admin.css",)
		}
		js = ('js/main.ajax.django.js', 'js/custom.admin.js',)

admin.site.register(Posting, AdminPosting)

views.py

from django.http import JsonResponse
from django.core import serializers
from .models import Posting

# ...

def ajax_testing(request):
	if request.method == 'POST':
		ids = request.POST.get('id');
		judul = request.POST.get('judul')
		penulis = request.POST.get('penulis')
		data1 = request.POST['isi']
		print(data1)
		data = Posting.objects.filter(judul=judul)
		if data:
			return JsonResponse({"status": "ok"})
		else:
			return JsonResponse({"status": "ko"})

	# data = Posting.objects.all()
	# return JsonResponse(serializers.serialize('json', data), safe=False)

urls.py (app)

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

urlpatterns = [
	# ...
	# View testing json rest
	url(r'^rest/', views.ajax_testing, name="ajax_testing"),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment