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.
{ "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.pydef 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.pyfrom 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.
Labels: Django, Django widget SelectMultiple
change the default filter choice from 'ALL'
class MyModelAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
if not request.GET.has_key('decommissioned__exact'):
q = request.GET.copy()
q['decommissioned__exact'] = 'N'
request.GET = q
request.META['QUERY_STRING'] = request.GET.urlencode()
return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)
Labels: Django
import urllib
def urldecode(query):
d = {}
a = query.split('&')
for s in a:
if s.find('='):
k,v = map(urllib.unquote, s.split('='))
try:
d[k].append(v)
except KeyError:
d[k] = [v]
return d
s = 'Cat=1&by=down&start=1827&start=1234&anotherCat=me%3Dow%7e'
print urldecode(s)
====================================================
prints out following and preserves the order of inputs for those keys given more than once as with 'start' key
{'start': ['1827', '1234'], 'anotherCat': ['me=ow~'], 'by': ['down'], 'Cat': ['1']}
What is Tropo?
Tropo is a new script-language focused API and deployment platform from Voxeo. Tropo's goal is to make it extremely easy for JavaScript, Ruby, Groovy, PHP and Python developers to create and deploy telephony and other communication applications.
The current release of Tropo is similar to Google App Engine. You write scripts which drive our communications API.
When you want to take or make calls, we run those scripts on servers in our cloud infrastructure. While running on our servers your scripts can use HTTP, web services, or other techniques to integrate with any other services or infrastructure.
Creating Tropo Applications
To implement a Tropo application, developers:
* Write a Tropo application in a supported scripting language
* Deploy their application on any web server
* Create a Tropo application at Tropo.com and link it to their script
* Test and debug their application using the application debugger
Write a Tropo Application
Tropo applications may be written in a number of supported scripting languages. At the time of launch, supported languages included:
* Ruby (.ruby, .truby, .rb, .trb)
* Python (.py, .tpy, .jython, .tjython, .jy, .tjy)
* Groovy (.groovy, .tgroovy, .gr, .tgr)
* PHP (.php, .tphp)
* JavaScript (.javascript, .js, .es)
File extensions are used by Tropo to identify the interpreter that should be used to execute your script at runtime. Supported extensions are listed above along with their interpreter type. The "t" versions of the extensions are meant to prevent accidental execution of your script in some hosted environments. Remember, Tropo wants to execute your script on our telephony servers when a call is started!
Deploy Your Application Script Files
Once written, you must deploy the resulting script file to a web server of your choice. You may use your own web server, or you may choose to host your file on the Tropo web servers within Voxeo's data centers ("Tropo Hosted Scripts").
If you choose to use Tropo web hosting for your files, you may upload and manage your files through the Tropo Hosted Scripts tools, or you may use our Tropo WebDAV Support to manage and edit your scripts directly from your favorite editor.
Create the Tropo Application
Go to Tropo.com and log into your account (create one if necessary). Once you log in, you will be presented with some Quick Links that allow you to manage your Applications, manage your Hosted Scripts, or review the Documentation. Choose "Applications" to setup an application linked to your script.
Introduction
- Simple way to implement dynamic image upload_to path based on object.It is now possible for the
upload_to
parameter of theFileField
orImageField
to be a callable, instead of a string. The callable is passed the current model instance and uploaded file name and must return a path.
Models.py
class Books(models.Model):
no=models.IntegerField()
class Collection(models.Model):
def imagepath(instance,filename):
val="Book_Media/" + str(instance.Books.no) + "/" + str(filename)
return val
Page=models.ForeignKey('Books')
image=models.ImageField(upload_to=imagepath)
Description:imagepath is the callable (in this case a function). It simply gets the 'no' from the instance of
Books
and uses that in the upload path. Images will be uploaded to paths like: Book_Media/1/djano.jpg
Labels: Django
Introduction:
Simple way to implement Ajax in Django with the help of Dojo toolkit.
1.Models.py
Create a model for Book
class Book(models.Model):
author = models.CharField(max_length = 60)
year = models.IntegerField()
ref_no =models.IntegerField()
2.Form.py
Create a ModelForm for 'Book' Models
Write a function for save the details of 'Book'
Import Dojo necessary packages to your html file
Import Ajax.js where we are going to write the ajax function.
Div 'result' for show the response(from form.py) after the form submission.
Write a function named as ValidateBook
Declare a variable 'kw'
Variable 'data' contains the response .
If the Book details storeded in database, then form.py will return '1' for confirmation
If Book details failed to validate , then error response will return.
class BookForm(ModelForm):
class Meta:
model=Book
def AddBook(request):
if request.method == 'POST':
form=BookForm(request.POST)
if form.is_valid():
form.save()# save Book
return HttpResponse ("1")#if Book object stored, return confirmation.
else:
return HttpResponse ("Please check the form data.")# if form validation failed
else:
form=BookForm()
return render_to_response("Register.html",{'Form':form})
3. Register.html
<script type="text/javascript" src="/path_to_dojo/dojo-release-1.2.0/dojo/dojo.js" djConfig="parseOnLoad:true"></script>
<script type="text/javascript" src="ajax.js" ></script>
<body>
<div id=”result”></div>
<div id=”FormDiv”>
<form id="AddBook">
{{Form}}
</form>
<input type="submit" onclick="return ValidateBook();">
<div>
</body>
4.Ajax.js
function ValidateBook()
{
var kw = {
form: dojo.byId("AddBook"),
url: "/book/add/",
load: function(data){
if (data==1)
{
dojo.byId("result").innerHTML="Book details has been registered successfully. ;
dojo.byId("FormDiv").innerHTML=""
}
else
{
dojo.byId("test").innerHTML = data;
}
},
error: function(data){
console.debug("An error occurred: ", data);
},
timeout: 5000,
form: "AddBook"
};
dojo.xhrPost(kw); //Servlet get argement with doPost
}
}
Introduction
Ubuntu is a great OS for use in both virtualisation hosts and in guest virtual machines and software appliances. Virtualization simply means the running of another OS within a host OS, through the usage of a special "hypervisor" application which handles everything about how the guest OS operates within (and with) the host system
Disable Apparmor:
/etc/init.d/apparmor stop
update-rc.d -f apparmor remove
Install XEN:
apt-get install ubuntu-xen-server
After installation of xen you should edit xorg.conf file.
Update xorg configuration.vim /etc/X11/ xorg.conf
Your original xorg.conf files looks
Now add the following line in xorg.confSection "Device"
Identifier "Configured Video Device"Section "Device"
Identifier "Configured Video Device"
Driver "i810"
- Note: Here i810 refers to graphics chipset.So check out your system graphics chipset.
Download 2.6.24-16-xen kernel To avoid network problem:
wget http://www.il.is.s.u-tokyo.ac.jp/~hiranotaka/linux-image-2.6.24-16-xen_2.6.24-16.30zng1_i386.deb
Replace the Ubuntu 2.6.24-16-xen kernel:
dpkg -i linux-image-2.6.24-16-xen_2.6.24-16.30zng1_i386.deb
- Reboot your system
Move tls file:
mv /lib/tls /lib/tls.disabled
Modify Modules:
Add the line in vim /etc/modules
loop max_loop=64
Directory for XEN:
mkdir /home/xen
Modify xen-tools.conf:
vim /etc/xen-tools/xen-tools.conf
install-method = debootstrap # method will change with respect to type of OS
dir = /home/xen
dhcp = 1
dist = hardy # Type of guest os
passwd = 1
mirror = http://192.168.1.36:9999/ubuntu/
- Reboot your system
Now Run
jayapal@kcs:~$ uname -r
2.6.24-16-xen
Create Guest OS:
jayapal@kcs:~$ xen-create-image --hostname=Guestos --ide --passwd
Note: You can give size, swap, Network settings, etc... to override settings in xen-tools.conf.
For more details jayapal@kcs:~$ man xen-create-image
After creating image file,Terminal will show message as :
Logfile produced at:
/var/log/xen-tools/Guestos.log
Guestos.cfg
vim /etc/xen/Guestos.cfg
kernel = '/boot/vmlinuz-2.6.24-16-xen'
ramdisk = '/boot/initrd.img-2.6.24-16-xen'
memory = '128'
vcpus = '2' #For dual-core CPU
root = '/dev/hda2 ro'
disk = [
'tap:aio:/home/xen/domains/Guestos/swap.img,hda1,w',
'tap:aio:/home/xen/domains/Guestos/disk.img,hda2,w',
]
vif = [ 'ip=192.168.2.10 mac=00:16:3E:C9:C2:6C' ]
To start the virtual machine:
xm create /etc/xen/Guestos.cfg
Using config file "/etc/xen/Guestos.cfg".
Started domain Guestosxm console Guestos
Guestos started and it will prompt for user login.To Stop the virtual machine:
xm shutdown Guestosfor more command see xm man
For Centos:
Download initrd.img and vmlinuz, then move in to /boot/ directory
wget http://mirror.centos.org/centos/5/os/i386/images/xen/initrd.img
wget http://mirror.centos.org/centos/5/os/i386/images/xen/vmlinuzMirror
http://mirror.centos.org/centos/5/os/i386/images/xen/
Source:
http://www.howtoforge.com/ubuntu-8.04-server-install-xen-from-ubuntu-repositories
Labels: ubuntu, Virtualization, xen
Procedure:
Download audit file and save inside your project application folder.
Edit models file
from django.db import models
import audit
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
salary = models.PositiveIntegerField()
history = audit.AuditTrail()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
If you need to view the audit information in the admin interface, simply add show_in_admin=True as an argument to AuditTrail.
Then run python manage.py sncdb in terminal to take effect
Testing:
Test1View.py
from myapp.models import Person
person = Person.objects.create(first_name='Jayapal', last_name='D', salary=50000)
person.history.count()
OutPut:
1
Test2View.py
from myapp.models import Person
person = Person.objects.create(first_name='Jayapal', last_name='D', salary=50000)
person.salary = 65000
person.save()
for item in person.history.all():
print "%s: %s" % (item, item.salary)
person2 = Person.objects.create(first_name='Sahab', last_name='Husain', salary=50000)
print "count:", person.history.count()
print "count of person2:",person2.history.count()
print "total count in table Person:",Person.history.count()
OutPut:
Jayapal D as of 2007-08-14 20:31:21.852000: 65000
Jayapal D as of 2007-08-14 20:30:58.959000: 50000
count: 2
count of person2: 1
total count of table Person: 3
Tracking Information:
As you can see, the audit trail is listed with the most recent state first. Each entry also inclues a timestamp when the edit took place. Saves and deletes are both tracked, and can be filtered on via Person.history.filter(_audit_change_type='_') . Do not use underscore, use 'I' for inserts, 'U' for updates, and 'D' for deletes. ForeignKeys? and OneToOneFields? are now supported both for saving and accessing the audit data. However, it does not archive the contents of the ForeignKey? table for the appropriate entries at the same time, and will fail if the ForeignKey? a given audit entry is related to is deleted (including if you're auditing the ForeignKey? table as well, it does not have a way to link the two audit tables together).
For More information Audit+Wiki
Labels: Django
The Django Debug Toolbar is a configurable set of panels that display various debug information about the current request/response and when clicked, display more details about the panel's content.
Currently, the following panels have been written and are working:
Django version
Request timer
A list of settings in settings.py
Common HTTP headers
GET/POST/cookie/session variable display
Templates and context used, and their template paths
SQL queries including time to execute and links to EXPLAIN each query
Cache stats
Logging output via Python's built-in logging module
DebugToolbar or see for latest source code
Copy folder in your python site-packages path (/usr/lib/python2.5/site-packages/debug_toolbar
Implementation
Edit your project settings.py file
DEBUG = True
MIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS = ('debug_toolbar',)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.version.VersionDebugPanel', 'debug_toolbar.panels.timer.TimerDebugPanel', 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel', 'debug_toolbar.panels.headers.HeaderDebugPanel', 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel', 'debug_toolbar.panels.template.TemplateDebugPanel', 'debug_toolbar.panels.sql.SQLDebugPanel', 'debug_toolbar.panels.cache.CacheDebugPanel', 'debug_toolbar.panels.logger.LoggingPanel',
)
Run your project and see django toolbar in template.
Screen Shots
Labels: Django
mod_wsgi is an Apache module for serving WSGI-based Python web applications from the Apache HTTP server. Django, along with almost every other Python web framework today, comes bundled with a backend for acting like a WSGI application. Discovering and trying out mod_wsgi really suprised me. It can take a massive beating, and outperforms mod_python in every practical aspect.
The setup
You will need a short Python "bootstrap" script to create a WSGI-handler for your Django project. Here is an example (call it wsgi_handler.py and place it in the root directory of your Django project - the one with manage.py and settings.py):
import sys
import os
import django.core.handlers.wsgi
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'projectname.settings'
application = django.core.handlers.wsgi.WSGIHandler()
Apache virtualhost to use mod_wsgi
Add the below lines before the endof virtualhost close tag in apache config file
WSGIScriptAlias / /home/user/projectname/wsgi_handler.py
WSGIDaemonProcess projectname user=user group=user processes=1 threads=10
WSGIProcessGroup projectname
Restart apache to take effect.
In the WSGIDaemonProcess line, you can easily manage the amount of system resources (measured in processes and threads) mod_wsgi should use. In my experience a single process with 10 threads will cover most small and medium loaded websites.
Why?
This is some of the reasons why you should ditch mod_python for mod_wsgi when hosting Django projects:
Faster
Less memory usage
Everyone hosting more than a couple of Django projects on a single Apache instance knows that Django projects squanders a bit with memory usage, and every single Apache child process will easily end up using 50 MB RAM.
mod_wsgi dedicates a process (or multiple processes) to a single interpreter for a single Django project, and keeps the memory usage low in the "normal" Apache child processes. On a server with 8 small Django projects, I went from using ~1500 MB RAM on Apache child processes to using 150 MB.
Secure
When using mod_python your Python interpreter will be running as the user running the Apache webserver itself (on Debian systems, the user is called www-data). Typically this will allow you to peek around in places where you do not want your users peeking. This is due to the fact that www-data must have read access to every file you use in your application (including settings/configuration/media files).
mod_wsgi addresses this problem by changing to a user id specified in the configuration file, and run your Python interpreter as another user than www-data, allowing you to lock down every project on your server to seperate user accounts.
The load times of the websites now served with mod_wsgi really surprised me. Normally a page would be served within 150-300 ms. This was reduced to load times in the range of 40-80 ms.
I also discovered that running mod_wsgi in embedded mode (as opposed to daemon mode) was not worth the effort. I didn't really see any difference between load times when using Django.
These points cover mod_wsgi running in daemon mode
Labels: Django