jqgrid "form editing" example in Python-Django


It tooks me  a lot of time to figure out jqgrid form editing add/edit/del the jqgrid table in Django/Python structure, as the similar topics I found in the internet always only discussed part of it, or half-way solution.  So after several days painful time, I finally have most part works. Now  summary it.

I use array from python to display in jqgrid.

Html:
<table id="list"></table>
<div id="pager"></div>

The javascript :
//This is correct way to get the array from python, even with syntax
//error highlighted in javascript
var sitedata = {{ siteArray }}
jQuery("#list").jqGrid({ datatype: local mtype: 'POST', //height: 450, autowidth: true, shrinkToFit: true, colNames:['Website', 'Year', 'Website Id', 'Create Date', 'Comment'], colModel :[ {name: 'site_name',index:'site_name', editable: true, width:100}, {name: 'year',index:'year', editable: true, width:40, sorttype:"int",search:true, template:yearTemplate}, {name: 'website_id',index:'website_id', editable: true, width:50, sorttype:"int"}, {name: 'create_date',index:'create_date', editable: true, width:40, sorttype:"date",formatter:"date", formatoptions:{srcformat:'Y/m/d', newformat:'d.m.Y'}, {name: 'comment',index:'comment', editable: true, width:100}, ], pager: '#pager', rowNum:20, rowList:[20,50,100], sortname: 'did', sortorder: "desc", multiselect: true, viewrecords: true, imgpath: 'themes/basic/images', caption: 'Devices list', height: 450, //the url below is the url of the page which processed by view.py, and defiend in urls.py editurl: "{% url views.site %}", });
 
// Code below is used to display the array data in jqgrid, more examples can be found here for (var i=0; i<=sitedata.length;i++) jQuery("#list").jqGrid('addRowData',i+1,sitedata[i]);

// Add the navigation buttons
     jQuery
("#list").jqGrid('navGrid', '#pager',{alerttop:1600, alertleft:512, add:true,edit:true,del:true,search:true}, { // Code below used to process the 403 Forbidden error as discussed later in this article checkOnSubmit:true, // Pop-up window to ask for confirmation to submit, only for edit
            closeAfterEdit:true,
reloadAfterSubmit:true, closeOnEscape:true, editData: {csrfmiddlewaretoken: '{{ csrf_token }}'}, afterSubmit: function(){location.relaod(true);} // Refresh the page to display the submitted data }, { closeAfterAdd:true, reloadAfterSubmit:true, closeOnEscape:true, editData: {csrfmiddlewaretoken: '{{ csrf_token }}'},
           afterSubmit: function(){location.relaod(true);} 
}, { closeOnEscape:true, delData: {csrfmiddlewaretoken: '{{ csrf_token }}'} }, {height: 230, reloadAfterSubmit: true} );

Python code:
view.py

from django.shortcuts import render_to_response
from django.http import HttpResponse
from djanog.template import ReqestContext 
from django.utils.safestring import mark_safe
import MySQLdb as mdb
def site(request): #code context_dict = {} #code #Check MySQLdb usage con = mdb.connect(host='', port='',user='',passwd='',db='',charset="utf8",use_unicode=True, init_command='SET NAMES UTF8') #--------jqgrid Add/Edit/Del row-------------------------- method = request.method # The variables from POST of jqgrid can be found in the " What is posted to the server " here oper = request.POST.get("oper") if oper is not None: year = request.POST.get("year") comment = request.POST.get("comment") website_id = request.POST.get("website_id") create_date_o = request.POST.get("create_date") # Modify the date format for database create_date = datetime.datetime.strptime(create_date_o,'%d.%m.%Y').strftime('%Y-%m-%d') if oper == 'add': try: #import pdb; pdb.set_trace() update(con, query_add_vmk(year,jq_vmk,comment,website_id,create_date)) return home(request) except ValueError: print "mysql Update() dose not work." elif oper == "edit": #code return home(request) #---------jqgrid Display data------------------------------- loadsites = response_sites(con, query_sites()) #The result from mysql needs to be processed as json format to be used by jqgrid context_dict['siteArray'] = mark_safe(json.dumps(loadsites)) #code return render_to_response("project/sites.html", context_dict, RequestContext(request),) #code context_dict = {} #code #Check MySQLdb usage con = mdb.connect(host='', port='',user='',passwd='',db='',charset="utf8",use_unicode=True, init_command='SET NAMES UTF8') #--------jqgrid Add/Edit/Del row-------------------------- method = request.method # The variables from POST of jqgrid can be found in the " What is posted to the server " here oper = request.POST.get("oper") if oper is not None: year = request.POST.get("year") comment = request.POST.get("comment") website_id = request.POST.get("website_id") create_date_o = request.POST.get("create_date") # Modify the date format for database create_date = datetime.datetime.strptime(create_date_o,'%d.%m.%Y').strftime('%Y-%m-%d') if oper == 'add': try: #import pdb; pdb.set_trace() update(con, query_add_vmk(year,jq_vmk,comment,website_id,create_date)) // query_add_vmk is a function with mysql query to add the data in the dtabase return home(request) except ValueError: print "mysql Update() dose not work." elif oper == "edit": #code #---------jqgrid Display data------------------------------- loadsites = response_sites(con, query_sites()) #The result from mysql needs to be processed as json format to be used by jqgrid context_dict['siteArray'] = mark_safe(json.dumps(loadsites)) #code return render_to_response("project/sites.html", context_dict, RequestContext(request),)


Now you can start to play with jqgrid. There are still a lot of issues and tricks, I will continue when I have time.

Explanation:
1. Avoid  csdf_token problem.
{
            closeAfterAdd:true,
            reloadAfterSubmit:true,
            closeOnEscape:true,
            editData: {csrfmiddlewaretoken: '{{ csrf_token }}'}
        }, 
2. Customer the position of warning pop-up window for form-editing:
This pop -up window is a reminder to "Select row" when edit/del a row.

{alerttop:1600, alertleft:512, add:true,edit:true,del:true,search:true}
Though this is not a good solution as the position is fixed. Will work to figure out a dynamic solution based on the position of the grid.

3. Refresh the page (different from reload the grid)
afterSubmit: function(){location.relaod(true);}
Add this option in the setting for action edit, add, or del. Then the data will refreshed from the server. You action will be reflected in the grid.

Reference:
1. The demos of jqgrid, with good example to load different type of source data to jqgrid:
http://www.trirand.com/blog/jqgrid/jqgrid.html
2. The playground of jqgrid, http://jsfiddle.net/jqJch/69/

Comments

Popular posts from this blog

install postgreSQL in ubuntu 16.04

timestamp with 16, 13 and 10 digits to Qlik date

install ipython in Cloudera VM using pip