Blogger Template by Blogcrowds.

Introduction

  • Implementation of dojo datagrid with editable cells, update cell values with the use of dojo xhrget method, then save the edited datagird and send data to server as josn format to update data in database.
Jsonformat
{ "identifier": "id", "label": "uniqueid", "items": [ {id: '1',image:'jai.png',name: 'Jayapal',address:'Trivandrum,Kerala,India',gender:'Male'}] }
DataGrid.html
  • First import necessary css and script for dojo
<style type="text/css">
@import "/{{MEDIA_URL}}/js/dojo/dojox/grid/_grid/tundraGrid.css";
@import "/{{MEDIA_URL}}/js/dojo/dijit/themes/tundra/tundra.css";
@import "/{{MEDIA_URL}}/js/dojo/dojo/resources/dojo.css";
@import "/{{MEDIA_URL}}/js/dojo/dojox/grid/resources/Grid.css";
@import "/{{MEDIA_URL}}/js/dojo/dojox/grid/resources/tundraGrid.css";
</style>
<script type="text/javascript" src="/PathToDojo/dojo/dojo.js" djConfig="parseOnLoad:true"></script>
  • Import select- All, None and Toggle function which is written by myself.
<script type="text/javascript" src="/{{MEDIA_URL}}/js/GridFunction.js"></script>
  • GridFunction.js

/*Function for select ALL in dojo grid*/
function SelectAll()
{
var grid=dijit.byId('GridTable');
var gridstore=dijit.byId('GridTable').store;
gridstore.fetch({onComplete:function(items,request)
{
var i;
for (i=0;i<grid.rowCount;i++)
{
gridstore.setValue(items[i],"Select" ,true);
}
}
});
}


/*Function for select NONE in dojo grid*/
function SelectNone()
{
var grid=dijit.byId('GridTable');
var gridstore=dijit.byId('GridTable').store;
gridstore.fetch({onComplete:function(items,request)
{
var i;
for (i=0;i<grid.rowCount;i++)
{
gridstore.setValue(items[i],"Select" ,false);
}
}
});
}


/*Function for select Toggle in dojo grid*/
function Toggle()
{
var grid=dijit.byId('GridTable');
var gridstore=dijit.byId('GridTable').store;
gridstore.fetch({onComplete:function(items,request)
{
var i;
for (i=0;i<grid.rowCount;i++)
if (gridstore.getValue(items[i],"Select")==true)
{
gridstore.setValue(items[i],"Select" ,false);
}
else if (gridstore.getValue(items[i],"Select")==false)
{
gridstore.setValue(items[i],"Select" ,true);
}
}
});
}
  • Function for store the datagrid after editing the diffeent cells in the data grid and data will be send to the server as json format.
<script type="text/javascript">
var fillStore = function(){
dijit.byId('GridTable').store._saveEverything = function(saveCompleteCallback, saveFailedCallback, newFileContentString){
console.log(newFileContentString);
dojo.xhrPost({
url: "/yourproject/application/",
postData: dojo.toJson(dojo.fromJson(newFileContentString)),
error: saveFailedCallback,
load: function(response, ioArgs)
{
alert(response) ;
dijit.byId('GridTable').store.save();
}
,
});
}
}

dojo.addOnLoad(fillStore);
</script>
  • Function for embedded image in datagrid.
<script type="text/javascript">
function CreateImage(value)
{

var imgtag=" <img title=\"Click here to zoom the image \" style=\"cursor:pointer; \" onclick= \" return ImagePopUp('"+value+"');\" src='/{{MEDIA_URL}}/Thumbnails/"+value+"' alt='NA' >";
return imgtag;
}
</script>
  • Html content along with ItemFileWriteStore for load the data json from the url mentioned.
  • You can find a script written just after table tag. That script will be triggered when any cell is edited in datagrid. The 'onApplyCellEdit' event returns New value, RowIndex, fieldtype. You can find more events here.
  • If you need to enable edit any cell, then you need to give editable="true". You need to double click the cell for edit. If you want to make the cells alwys as editable field then we need to give as alwaysEditing='true'.
  • For embedded image in datagrid then we need to call a javascript while loading. For that we used formatter="CreateImage" which will return image tag. Formatter A JavaScript function that is called which returns the value to be shown in the cell. The value from the data store is passed as a parameter to the function. The returned value that is inserted into the page can be any legal HTML
<BODY class="tundra"><span dojoType="dojo.data.ItemFileWriteStore" jsId="store" url="/yourpath/getJson/">
</span>
<div id="SelectMenu">Select <a href="#" onclick="SelectAll();"> All </a><a href="#" onclick="SelectNone();"> None </a> <a href="#" onclick="Toggle();">Toggle </a></div>
<table id="GridTable" dojoType="dojox.grid.DataGrid"
jsId="grid6"
store="store"
query="{ uniqueid: '*' }"
rowsPerPage="20"
clientSort="true"
style="width: 100%;"
height="85%"
rowSelector="20px">
<script type="dojo/connect" event="onApplyCellEdit" args="Name,rowIndex,fieldType">

if (fieldType=="Name")
{
dojo.xhrGet( {
url: "/URL/getAddress/"+Name+"/",
load: function(data){
if (data)
{
if (data== -1)
{
var item = grid6.getItem(rowIndex);
var type = store.getValue(item,"address",null);
rowIndex.customStyles += "color:red;";
}
else
{
gridstore=dijit.byId('GridTable').store
gridstore.fetch({onComplete:function(items,request)
{
gridstore.setValue(items[rowIndex],"address" ,data);

}
});
}
}
else { dojo.byId("test").innerHTML = data;}

},
error: function(data){ console.debug("An error occurred: ", data);},
timeout: 10000,
});
}

</script>
<thead>
<tr>
<th width="1%" field="Select" name="Select" width="5%" editable="true" cellType="dojox.grid.cells.Bool">
<div dojoType="dijit.form.CheckBox" id="Select" name="Select" value="false" />
</th>
<th width="1%" field="id">Sl No</th>
<th width="5%" alwaysEditing='true' field="name" alwaysEditing='true' editable="true">Name</th>
<th width="5%" formatter="CreateImage" field="image">Image</th>
<th width="10%" alwaysEditing='true' editable="true" field="address">Address</th>
<th width="8%" alwaysEditing='true' field="gender" cellType="dojox.grid.cells.Select"
options="Select,Male,Female"
editable="true" >Gender</th>
</tr>
</thead>
</table>
<center><button dojoType="dijit.form.Button" onclick="dijit.byId('GridTable').store.save();">Save Selected items</button></center>
Final html page looks like
<style type="text/css">
@import "/{{MEDIA_URL}}/js/dojo/dojox/grid/_grid/tundraGrid.css";
@import "/{{MEDIA_URL}}/js/dojo/dijit/themes/tundra/tundra.css";
@import "/{{MEDIA_URL}}/js/dojo/dojo/resources/dojo.css";
@import "/{{MEDIA_URL}}/js/dojo/dojox/grid/resources/Grid.css";
@import "/{{MEDIA_URL}}/js/dojo/dojox/grid/resources/tundraGrid.css";
</style>

<script type="text/javascript" src="/{{MEDIA_URL}}/js/GridFunction.js"></script>
<script type="text/javascript" src="/PathToDojo/dojo/dojo.js" djConfig="parseOnLoad:true"></script>
<script type="text/javascript">
// this function is used to store the edited datagrid store and sent data to sever in json format
var fillStore = function(){
dijit.byId('GridTable').store._saveEverything = function(saveCompleteCallback, saveFailedCallback, newFileContentString){
console.log(newFileContentString);
dojo.xhrPost({
url: "/yourproject/application/",
postData: dojo.toJson(dojo.fromJson(newFileContentString)),
error: saveFailedCallback,
load: function(response, ioArgs)
{
alert(response) ;
dijit.byId('GridTable').store.save();
}
,
});
}
}

dojo.addOnLoad(fillStore);
</script>
<script type="text/javascript">
function CreateImage(value)
{

var imgtag=" <img title=\"Click here to zoom the image \" style=\"cursor:pointer; \" onclick= \" return ImagePopUp('"+value+"');\" src='/{{MEDIA_URL}}/Thumbnails/"+value+"' alt='NA' >";
return imgtag;
}
</script>

<span dojoType="dojo.data.ItemFileWriteStore" jsId="store" url="/rlvd/getViolationJson/">
</span>
<BODY class="tundra">
<div id="SelectMenu">Select <a href="#" onclick="SelectAll();"> All </a><a href="#" onclick="SelectNone();"> None </a> <a href="#" onclick="Toggle();">Toggle </a></div>
<table id="GridTable" dojoType="dojox.grid.DataGrid"
jsId="grid6"
store="store"
query="{ uniqueid: '*' }"
rowsPerPage="20"
clientSort="true"
style="width: 100%;"
height="85%"
rowSelector="20px">
<script type="dojo/connect" event="onApplyCellEdit" args="Name,rowIndex,fieldType">

if (fieldType=="Name")
{
dojo.xhrGet( {
url: "/URL/getAddress/"+Name+"/",
load: function(data){
if (data)
{
if (data== -1)
{
var item = grid6.getItem(rowIndex);
var type = store.getValue(item,"address",null);
rowIndex.customStyles += "color:red;";
}
else
{
gridstore=dijit.byId('GridTable').store
gridstore.fetch({onComplete:function(items,request)
{
gridstore.setValue(items[rowIndex],"address" ,data);

}
});
}
}
else { dojo.byId("test").innerHTML = data;}

},
error: function(data){ console.debug("An error occurred: ", data);},
timeout: 10000,
});
}

</script>
<thead>
<tr>
<th width="1%" field="Select" name="Select" width="5%" editable="true" cellType="dojox.grid.cells.Bool">
<div dojoType="dijit.form.CheckBox" id="Select" name="Select" value="false" />
</th>
<th width="1%" field="id">Sl No</th>
<th width="5%" alwaysEditing='true' field="name" alwaysEditing='true' editable="true">Name</th>
<th width="5%" formatter="CreateImage" field="image">Image</th>
<th width="10%" alwaysEditing='true' editable="true" field="address">Address</th>
<th width="8%" alwaysEditing='true' field="gender" cellType="dojox.grid.cells.Select"
options="Select,Male,Female"
editable="true" >Gender</th>
</tr>
</thead>
</table>
<center><button dojoType="dijit.form.Button" onclick="dijit.byId('GridTable').store.save();">Save Selected items</button></center>
Views.py
def SaveJson(request)
    if request.POST:
         getJson=request.POST# get the json from request
        qJson=getJson.copy()# copy the request.POST
         jsonValues=qJson.items()[0][0]
         json=simplejson.loads(jsonValues)# read the json using simplejson
         for item in json["items"]:
            data=SomeModel(name=str(item['name']),address=str(item['address']))
             data.save()
    return HttpResponse("Updated Successfully")

Introduction

  • This document helps you to reuse Django admin part FilteredSelectMultiple widget in our application. For that we need to do the following simple steps.

Models.py
  • Here model Student has many to many field to Subjects. In this case a student can have infinite subjects.
class Student(models.Model):
    name=models.CharField(max_length=100)
    subject=ManyToManyField(Subjects)
class Subjects(models.Model):
    sub_name=models.CharField(max_length=100)
    desc=models.CharField(max_length=100)
Views.py
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.forms import ModelForm
from django import forms

class StudentForm(ModelForm):
    subject=forms.ModelMultipleChoiceField(Subjects.objects.all(),widget=
FilteredSelectMultiple("Subjects",False,attrs={'rows':'10'}))
    class Meta:
        model= Student
def Form(request):
    stud_form=StudentForm()
    if request.POST:
        stud_form=StudentForm(request.POST)
        stud_form.save()
        return render_to_response("success.html")
    else:
        return render_to_response("form.html",{' stud_form': stud_form}


jsi18n.js
  • You can load the above script from admin part. please check the url http://localhost/yourproject/admin/jsi18n/. The problem is only admin user can load tis url, so i copied this script in our js folder, since all out enduser need to use this widget.

/* gettext library */
// This function is copied from django admin path

var catalog = new Array();

function pluralidx(count) { return (count == 1) ? 0 : 1; }


function gettext(msgid) {
var value = catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
}

function ngettext(singular, plural, count) {
value = catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value[pluralidx(count)];
}
}

function gettext_noop(msgid) { return msgid; }

function interpolate(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
}

Style.css
  • css for load default style with images for the widget. Please copy all necessary images(names mentioned in css) form django admin media path to your image directory.
/*css for admin widgets*/

/*for FilteredSelectMultiple*/
.selector {
width: 580px;
float: left;
}

.selector select {
width: 270px;
height: 8em;
}

.selector-available, .selector-chosen {
float: left;
width: 270px;
text-align: center;
margin-bottom: 5px;
}

.selector-available h2, .selector-chosen h2 {
border: 1px solid #ccc;
font-family:"Lucida Grande","DejaVu Sans","Bitstream Vera Sans",Verdana,Arial,sans-serif;
font-size:11px;
}

.selector .selector-available h2 {

background: #a6a077 url(/images/admin/nav-bg.gif) bottom left repeat-x;
color: white;
}
.selector .selector-chosen h2 {
background: #A29A63 url(/images/admin/default-bg.gif) repeat-x scroll left top;
color: white;
}


.selector .selector-filter {
background: white;
border: 1px solid #ccc;
border-width: 0 1px;
padding: 3px;
color: #999;
font-size: 10px;
margin: 0;
text-align: left;
}

.selector .selector-chosen .selector-filter {
padding: 4px 5px;
}

.selector .selector-available input {
width: 230px;
}

.selector ul.selector-chooser {
float: left;
width: 22px;
height: 50px;
background: url(/admin/chooser-bg.gif) top center no-repeat;
margin: 8em 3px 0 3px;
padding: 0;
}

.selector-chooser li {
margin: 0;
padding: 3px;
list-style-type: none;
}

.selector select {
margin-bottom: 5px;
margin-top: 0;
}

.selector-add, .selector-remove {
width: 16px;
height: 16px;
display: block;
text-indent: -3000px;
}

.selector-add {
background: url(/images/admin/selector-add.gif) top center no-repeat;
margin-bottom: 2px;
}

.selector-remove {
background: url(/images/admin/selector-remove.gif) top center no-repeat;
}

a.selector-chooseall, a.selector-clearall {
display: block;
width: 6em;
text-align: left;
margin-left: auto;
margin-right: auto;
font-weight: bold;
color: #666;
padding: 3px 0 3px 18px;
}

a.selector-chooseall:hover, a.selector-clearall:hover {
color: #036;
}

a.selector-chooseall {
width: 7em;
background: url(/images/admin/selector-addall.gif) left center no-repeat;
}

a.selector-clearall {
background: url(/images/admin/selector-removeall.gif) left center no-repeat;
}

.selector select {
font-family:"Lucida Grande",Verdana,Arial,sans-serif;
font-size:11px;
font-weight:normal;
}
.selector h2 {
margin-bottom:0; /*override dojo style*/
}


Form.html
<!-- Here ADMIN_MEDIA_PREFIX is path to django admin media -->
<script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/core.js"></script>
<script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/getElementsBySelector.js"></script>
<script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/actions.js"></script>
<script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/SelectBox.js"></script>
<script type="text/javascript" src="{{ADMIN_MEDIA_PREFIX}}js/SelectFilter2.js"></script>
<script type="text/javascript" src="/{{MEDIA_URL}}/js/jsi18n.js"></script>
<link rel="stylesheet" type="text/css" href="/css/style.css" >
<body>
    <form action="." method="POST">
        {{form_as.table}}
        <button type="SUBMIT">Submit</button>
    </form>
</body>
ScreenShots.

Newer Posts Older Posts Home