Modify object data by write Custom Renderer in Django Rest Framework

Modify object data by write Custom Renderer in Django Rest Framework

When we need to modify object or results from DRF / Django Rest Framework, all we need just write a custom JSON Renderer like below : 1234567891011121314class JGridJSONRenderer(renderers.JSONRenderer):     def render(self, data, accepted_media_type=None, renderer_context=None):         new_rows = []         # Name the object list         …

+ Read More

Solve issue Fullcalendar count two day as one day

Solve issue Fullcalendar count two day as one day

This is not bug. When we try to add day in March with start 10-03-2015T10:00:00 and end 11-03-2015T02:00:00, then it will showing one day instead of two day. To solve this issue, we need to put nextDayThreshold: 1nextDayThreshold: "00:00" To make the next day threshold every 00:00

Counting number contain 14 on n-digit number in less than 1 second

Counting number contain 14 on n-digit number in less than 1 second

My fellow Adiyat in our company POLATIC bug me with this question “How to counting number contain 14 in 10 millions numbers less than 1 second?”. Then I thought, it’s easy, let give python a shot! 1print len([x for x in range(0, 10000000) if str(x).find(’14’) > -1]) With result “590040” it’s takes 9.6s based on …

+ Read More

Django unit test formset

Django unit test formset

When testing page that contains formset in Django using unit test, we may encounter : 1ValidationError: [u’ManagementForm data is missing or has been tampered with’] This is happend because we POST data without required FORMSET hidden value in form. To solve this issue, inspect element on your formset and insert hidden value in payload data. …

+ Read More

Example make reusable javascript app for modal progress bootstrap

Example make reusable javascript app for modal progress bootstrap

This is example build reusable app in Javascript for modal progress in Boostrap: 123456789101112131415/**  * Re-usable app for modal box progress  */ var progressBox; progressBox = progressBox || (function() {     var pleaseWaitDiv =  $(‘<div class="modal hide" id="pleaseWaitDialog" data-backdrop="static" data-keyboard="false"><div class="modal-header"><h1>Processing…</h1></div><div class="modal-body"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div></div>’);     return {     …

+ Read More

How to hide search toolbar in Datatables

How to hide search toolbar in Datatables

Here is a quick snippet to hide search toolbar in datatables and working along with Bootstrap 1234var settings = {             sDom: ‘lrt<"col-sm-6"i><"col-sm-6"p>’,             serverSide : true, …

Set bootstrap datetimepicker input value date

Set bootstrap datetimepicker input value date

Here is a quick way to set value bootstrap datetimepicker input with date object: 123456$("#id_start_date, #id_end_date").datetimepicker({     format: "DD-MM-YYYY hh:mm" }); $(‘#id_start_date’).data("DateTimePicker").setDate(start); $(‘#id_end_date’).data("DateTimePicker").setDate(end);

Datatables make link in row records

Datatables make link in row records

Here is a quick snippet to make record as links in Datatables : 12345678columns : [               {                 "mRender": function ( data, type, full ) {                  // ‘full’ is the row’s data object, …

+ Read More

Change / Reset / Update Key Pem Amazon EC2 Simple

Change / Reset / Update Key Pem Amazon EC2 Simple

Here are simple tricks to change or update key PEM in Amazon EC2. At this example, I’m using Ubuntu. To reset or change key pem, all you need just follow this simple steps: Let say, currently we have SERVER_01 and KEYPEM_01. 1234561. Launch a new instances using "launch more like this" (right-click on instances) 2. …

+ Read More

Django check related model and check field if exists in model

Django check related model and check field if exists in model

We can check if the field is related model in Model by : 1model._meta.get_field("name_of_field").get_internal_type() == "ForeignKey" Then we can check if the field name is exists in model by : 1model._meta.get_field_by_name(_name) Some example code: 123456789101112131415if self.model._meta.get_field(field_name).get_internal_type() == "ForeignKey":     # get related model     # http://stackoverflow.com/questions/10347210/django-foreign-key-get-related-model     related_model = self.model._meta.get_field(field_name).rel.to     …

+ Read More

Mapping Ajax Filter and Search Datatables to Django with Rest Framework

Mapping Ajax Filter and Search Datatables to Django with Rest Framework

Datatables sending ajax parameter for filtering and search in very complicated way. Which we need to mapping and parse based on each column. Some example request : 1http://localhost:8000/api/somemodel/?format=json&sEcho=4&iColumns=7&sColumns=%2C%2C%2C%2C%2C%2C&iDisplayStart=0&iDisplayLength=10&mDataProp_0=&sSearch_0=&bRegex_0=false&bSearchable_0=true&mDataProp_1=cif&sSearch_1=22222&bRegex_1=false&bSearchable_1=true&mDataProp_2=name&sSearch_2=&bRegex_2=false&bSearchable_2=true&mDataProp_3=gender&sSearch_3=&bRegex_3=false&bSearchable_3=true&mDataProp_4=ktp&sSearch_4=&bRegex_4=false&bSearchable_4=true&mDataProp_5=location&sSearch_5=&bRegex_5=false&bSearchable_5=true&mDataProp_6=&sSearch_6=&bRegex_6=false&bSearchable_6=true&sSearch=&bRegex=false I have no idea about where the filtering and search query come from in this request. Therefore, we need to auto-mapping it by : 123456789101112131415161718import re from …

+ Read More

Disable sort on first column in Jquery Datatables

Disable sort on first column in Jquery Datatables

Dunno if this is bug or not, but disable sort in HTML nor Javascript will not affect for first column sorting in Datatables. The solution just define bSort = false 123456var table = $(‘#table-index’).dataTable({             serverSide : true,             sAjaxSource : url,       …

+ Read More

Solve ScrollTop Jquery not working in Boostrap because overflow:auto

Solve ScrollTop Jquery not working in Boostrap because overflow:auto

Yes, ScrollTop Jquery not working in Boostrap because overflow:auto. To solve this, we need to use div that using “overflow:auto” and solve by : 123456789101112<script type="text/javascript">            $(document).ready(function() {                                 /* smooth scrolling for scroll to …

+ Read More

Jquery Datatables modify fnserverData and pagination

Jquery Datatables modify fnserverData and pagination

Here is a quick snippet for custom AJAX data for Jquery datatables : 1234567891011121314151617181920212223242526272829303132 var table = $(‘#table-index’).dataTable({                 "serverSide": true,                 "searching": false,                 "ordering": false,                 …

+ Read More

Using format instead of %s for string replacement

Using format instead of %s for string replacement

Usually we use “%s” for string replacement in Python: 1"asddas %s" % (‘hello’,) There is better way to do it: 123"hello {a} {b} {c}".format(a=’error’, b=’hello’, c=’world’) "hello {0} {1} {2}".format("hello", "world", "fine") "hello {}".format("hello")

Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commit each, respectively.

Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commit each, respectively.

I got this problem: 123456λ git status On branch master Your branch and ‘origin/master’ have diverged, and have 1 and 1 different commit each, respectively.   (use "git pull" to merge the remote branch into yours) nothing to commit, working directory clean Solution 12λ git reset –hard origin/master HEAD is now at 63813ef fix localdb

Git checkout track from remote branch

Git checkout track from remote branch

Let’s say somebody already push their branch in remote called “finances”. We want to fetch and working on this branch from our local. So, the solution : 12345git fetch –all Fetching origin From github.com:polatic/vasham-erp  * [new branch]      finance    -> origin/finance Then, we checkout with tracking 123git checkout -t origin/finance Branch finance set …

+ Read More

Accelerate django development server with django-devserver

Accelerate django development server with django-devserver

As we know what django development server running on single thread. This is make development a bit slow. There is some alternative, by using django-devserver Here is the quickstep: 1. Install the app 1pip install git+git://github.com/nealtodd/django-devserver 2. Edit your local_settings.py 12345INSTALLED_APPS =  (‘devserver’,) + INSTALLED_APPS MIDDLEWARE_CLASSES = MIDDLEWARE_CLASSES + (    ‘devserver.middleware.DevServerMiddleware’, ) 3. Then …

+ Read More

Solve Django Filter queryset result duplicates with Pagination

Solve Django Filter queryset result duplicates with Pagination

When we filter using multiple filter and mixed with django pagination, somehow the results are duplicates. This is incorrect. Apparently, looking at the source code https://github.com/alex/django-filter/blob/master/django_filters/filters.py#L105, I found this line: 1234q = Q() for v in value:     q |= Q(**{self.name: v}) return qs.filter(q).distinct() By default, django-filter not using “AND” condition and that’s why …

+ Read More

Setup Django and Timezone follow server datetime (Ubuntu)

Setup Django and Timezone follow server datetime (Ubuntu)

Here is quickfix to setup Django working with server timezone. 1. Set Server Timezone Check by : 12date Mon Jan  5 10:54:38 WIB 2015 If this not correct or you want to change server timezone, then edit “/etc/timezone” 1Asia/Jakarta Then do : 12sudo dpkg-reconfigure –frontend noninteractive tzdata date Now you should see the updated server …

+ Read More