SlideShare a Scribd company logo
1 of 45
Django - Sql Alchemy - JQuery

         Rafie Tarabay

         eng_rafie@mans.edu.eg
Others    Safary    Chrome      Firefox    IE


                    JQuery
                                                              Oracle




                                                Sql Alchemy
         My Application                                       MySql




                    Django
                                                              MSSql
                   Google App
Apache    IIS                    Tornado   Django
                     Server
SQL Alchemy
To write SQL query compatible with
     all databases using ORM
Creating Table, Class and Mapper
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class User(Base):
     __tablename__ = ’users’
     id = Column(Integer, primary_key=True)
    name = Column(’f2’, String(50))
    fullname = Column(’f3’, String(50))
    password = Column(’f4’, String(50))

    def __init__(self, name, fullname, password):
         self.name = name
         self.fullname = fullname
         self.password = password

    def __repr__(self):
         return "<User(’%s’,’%s’, ’%s’)>" % (self.name, self.fullname, self.password)
Creating a Session to DB
from sqlalchemy.orm import sessionmaker

engine = create_engine(’sqlite:///:memory:’, echo=True)
Session = sessionmaker(bind=engine)




For Other DB Connections:
•   create_engine(’mysql://scott:tiger@localhost/foo’)
•   create_engine(’oracle://scott:tiger@127.0.0.1:1521/sidname’)
•   create_engine(’mssql://mydsn’)
•   create_engine(’sqlite:////absolute/path/to/foo.db’)
Adding new Objects
Add Row
ed_user = User(’ed’, ’Ed Jones’, ’edspassword’)
session.add(ed_user)

Edit Row
ed_user.password = ’f8s7ccs’

Add Batch
session.add_all([
      User(’wendy’, ’Wendy Williams’, ’foobar’),
          User(’mary’, ’Mary Contrary’, ’xxg527’),
          User(’fred’, ’Fred Flinstone’, ’blah’)+)

Apply Changes
session.commit()
session.rollback()
Query
our_user = session.query(User).filter_by(name=’ed’).first()

for name, in session.query(User.name).filter(User.fullname==’Ed Jones’):
     print name

for user in session.query(User).filter(User.id>5).filter(User.fullname==’Ed’):
   print user

for instance in session.query(User).order_by(User.id):
      print instance.name, instance.fullname

Note
You can control the names using the label() construct for scalar attributes and
   aliased() for class constructs:
user_alias = aliased(User, name=’user_alias’)
user_alias.name.label(’name_label’)
Common Filter Operators
equals:        query.filter(User.name == ’ed’)
not equals:     query.filter(User.name != ’ed’)
LIKE:         query.filter(User.name.like(’%ed%’))
IN: query.filter(User.name.in_(*’ed’, ’wendy’+))
Nested SQL:
query.filter(User.name.in_(session.query(User.name).filter(User.name.like(’%ed%’))))

NOT IN: query.filter(~User.name.in_(*’ed’, ’wendy’, ’jack’+))
IS NULL: filter(User.name == None)
IS NOT NULL: filter(User.name != None)
AND:
from sqlalchemy import and_
filter(and_(User.name == ’ed’, User.fullname == ’Ed Jones’))
# or call filter()/filter_by() multiple times
filter(User.name == ’ed’).filter(User.fullname == ’Ed
OR:
from sqlalchemy import or_
filter(or_(User.name == ’ed’, User.name == ’wendy’))
Parameter
session.query(User).filter("id<:value and name=:name").
       params(value=224, name=’fred’).order_by(User.id).one()

session.query(User).from_statement("SELECT * FROM users where
   name=:name").params(name=’asfasdf’)

session.query("id", "name", "thenumber12")
.from_statement("SELECT id, name, 12 as thenumber12 FROM users
   where name=:name").params(name='ed').all()
Count
session.query(User).filter(User.name.like('%ed')).count()
Building a Relationship
>>> from sqlalchemy import ForeignKey
>>> from sqlalchemy.orm import relationship, backref
>>> class Address(Base):
... __tablename__ = 'addresses'
... id = Column(Integer, primary_key=True)
... email_address = Column(String, nullable=False)
... user_id = Column(Integer, ForeignKey('users.id'))
...
... user = relationship(User, backref=backref('addresses', order_by=id))
...
... def __init__(self, email_address):
...    self.email_address = email_address
...
... def __repr__(self):
...    return "<Address('%s')>" % self.email_address
  ==================================================================================
class User(Base):
# ....
       addresses = relationship(Address, order_by=Address.id, backref="user")
Notes
• The above class introduces a foreign key constraint
  which references the users table. This defines for
  SQLAlchemy the relationship between the two tables
  at the database level.
• The relationship between the User and Address classes
  is defined separately using the relationship() function,
  which defines an attribute user to be placed on the
  Address class, as well as an addresses collection to be
  placed on the User class. Such a relationship is known
  as a bidirectional relationship.
• We free to not define a backref, and to define the
  relationship() only on one class and not the other.
Working with Related Objects
• jack = User(’jack’, ’Jack Bean’, ’gjffdd’)
• jack.addresses =
  [Address(email_address='jack@google.com'), Addr
  ess(email_address='j25@yahoo.com')]
Another Method



 SQL EXPRESSION
Connection
from sqlalchemy import create_engine
engine = create_engine(’sqlite:///:memory:’, echo=True)

Create Table
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
metadata = MetaData()
users = Table(’users’, metadata,
    Column(’id’, Integer, primary_key=True),
    Column(’name’, String),
    Column(’fullname’, String),
    )
addresses = Table(’addresses’, metadata,
    Column(’id’, Integer, primary_key=True),
    Column(’user_id’, None, ForeignKey(’users.id’)),
    Column(’email_address’, String, nullable=False)
    )
metadata.create_all(engine)

Insert Data
We Have 4 methods
Method 1
conn = engine.connect()
ins = users.insert().values(name=’jack’, fullname=’Jack Jones’)
result = conn.execute(ins)
result.inserted_primary_key
Method 2
conn = engine.connect()
conn.execute(addresses.insert(), [
       ,’user_id’: 1, ’email_address’ : ’jack@yahoo.com’-,
       ,’user_id’: 1, ’email_address’ : ’jack@msn.com’-,
       ,’user_id’: 2, ’email_address’ : ’www@www.org’-,
       ,’user_id’: 2, ’email_address’ : ’wendy@aol.com’-,
      ])
Method 3
result = engine.execute(users.insert(), name=’fred’, fullname=“Flintstone")
Method 4
metadata.bind = engine
result = users.insert().execute(name="mary", fullname="Mary Contrary")
Delete
conn.execute(users.delete().where(users.c.name > ’m’))
Connection /Connectionless
We’re executing our Insert using a Connection
  (Method1,2).
Or allow you to not have to deal with the
  connection part. You can execute in the
  connectionless style, using the engine, which
  opens and closes a connection for you
  (Method 3,4)
Query
Ex1
sql = select([users, addresses], users.c.id==addresses.c.user_id)
for row in conn.execute(sql):
         print row
Ex2
s = select([(users.c.fullname + ", " + addresses.c.email_address).label(’title’)+,
     and_(
            users.c.id==addresses.c.user_id,
            users.c.name.between(’m’, ’z’),
         or_(
            addresses.c.email_address.like(’%@aol.com’),
            addresses.c.email_address.like(’%@msn.com’)
             )
          )
        )
print conn.execute(s).fetchall()
Normal Query
from sqlalchemy.sql import text
 s = text(""“
          SELECT users.fullname || ’, ’ || addresses.email_address AS title
          FROM users, addresses
          WHERE users.id = addresses.user_id AND users.name BETWEEN :x AND :y AND
                 (addresses.email_address LIKE :e1 OR addresses.email_address LIKE :e2)
         """)
print conn.execute(s, x=’m’, y=’z’, e1=’%@aol.com’, e2=’%@msn.com’).fetchall()

hybrid approach
s = select(["users.fullname || ’, ’ || addresses.email_address AS title"],
            and_(
                "users.id = addresses.user_id",
                "users.name BETWEEN ’m’ AND ’z’",
                "(addresses.email_address LIKE :x OR addresses.email_address LIKE :y)"
             ),
             from_obj=*’users’, ’addresses’+
         )
print conn.execute(s, x=’%@aol.com’, y=’%@msn.com’).fetchall()
Transaction
# method_a starts a transaction and calls method_b
def method_a(connection):
      trans = connection.begin() # open a transaction
      try:
      method_b(connection)
      trans.commit() # transaction is committed here
      except:
      trans.rollback() # this rolls back the transaction unconditionally
      Raise


# method_b also starts a transaction
def method_b(connection):
      trans = connection.begin() # open a transaction - this runs in the context of method_a’s try:
      connection.execute("insert into mytable values (’bat’, ’lala’)")
      connection.execute(mytable.insert(), col1=’bat’, col2=’lala’)
      trans.commit() # transaction is not committed yet
      except:
      trans.rollback() # this rolls back the transaction unconditionally
      Raise


# open a Connection and call method_a
conn = engine.connect()
method_a(conn)
JQuery

To write JavaScript Compatible with
          all web browsers
Compare onLoad & Ready
window.onload :                     work only if all page +Images+Swf loaded


Solution
<script type="text/JavaScript">
jQuery(document).ready(function()
    {
    alert(‘All TextPage Loaded’);
    }
);
</script>
Select Element
<script type="text/JavaScript” src=“jquery.min.js"></script>
<a href="/category">Category</a>
<ul id="nav“ class=“ClassZ”>
<li><a href="#anchor1">Anchor 1</a></li>
<li><a href="#anchor2">Anchor 2</a></li>
<li><span><a href="#anchor3">Anchor 3</a></span></li>
</ul>

jQuery('#nav’)
jQuery('#nav li > a'); // This selects two elements, as expected
jQuery('#content span a'); // all anchor within all span elements within #content
jQuery(‘.ClassZ'); // Select elelments with calss= classZ
jQuery('li:eq(1)'); //selects the second element in the set of <li>'s by index, index starts at 0
Attributes Help In Selections
:first   Matches the first selected element
:last    Matches the last selected element
:even    Matches even elements (zero-indexed)
:odd     Matches odd elements (zero-indexed)
:eq(n)   Matches a single element by its index (n)
:lt(n)   Matches all elements with index below n
:gt(n)   Matches all elements with index above n
Selecting Elements Based on What
               They Contain
<span>Hello Bob!</span>
// Select all SPANs with 'Bob' in:
jQuery('span:contains("Bob")');        //it’s case sensitive

jQuery('div:not(#content)'); // Select all DIV elements except #content



To test for nested elements, you can use the :has() filter.
jQuery('div:has(p a)');
Selecting Elements Based on Their
                  Visibility
jQuery('div:hidden');
jQuery('p:visible').hide(); // Hiding only elements that are currently visible

if (jQuery('#elem').is(':hidden')) {
                                       // Do something conditionally
                                  }
Selecting Form Elements by Type
:text           <input type="text" />
:password       <input type="password" />
:radio          <input type="radio" />
:checkbox       <input type="checkbox" />
:submit         <input type="submit" />
:image          <input type="image" />
:reset          <input type="reset" />
:button         <input type="button" />
:file           <input type="file" />
:hidden         <input type="hidden" />

jQuery(':text'); //select all text inputs,
jQuery(':input:not(:hidden)'); // Selects all input elements not hidden.
Navigate in DOM
jQuery('li:eq(1)').next()           //selects the third <li>
jQuery('li:eq(1)').prev()           //selects the first <li>
jQuery('li:eq(1)').parent()        //selects the <ul>
jQuery('li:eq(1)').nextAll()      //selects all the <li>s after the second <li>
jQuery('li:eq(1)').prevAll()       //selects all the <li>s before the second <li>
jQuery('li:eq(1)').parent().children()              //selects all <li>s
jQuery('li:eq(1)').parent().children(':last')      //selects the last <li>
Apply Effect on Selected Elements
jQuery('div'). css('border','1px solid #993300');

//add a class attribute with a value of updatedContent to all divs
jQuery('div')[0].addClass("updatedContent");

//hide all divs on the page
jQuery('div').hide();

//update the text contained inside of all divs
jQuery('div').text('new content');

//show all divs on the page
jQuery('div').show();

jQuery('a').length
jQuery('input',$('form')).length
jQuery('input','body').length
jQuery('input',document.forms[0]).length

jQuery('#username').focus();     //<input name="username" id="username" type="text" />
jQuery('#username'). val();
<style>
table tr.even {background: #CCC;}
<style>

<table>
<tr><td>0</td><td>even</td></tr>
<tr><td>1</td><td>odd</td></tr>
<tr><td>2</td><td>even</td></tr>
<tr><td>3</td><td>odd</td></tr>
<tr><td>4</td><td>even</td></tr>
</table>

jQuery('tr:even').addClass('even');
Inject DOM/Remove/Replacing/Copy
Inject Elements
appendTo()     Example jQuery('<p><a>jQuery</a></p>'). appendTo('body');
insertAfter()
insertBefore()

Remove Element
jQuery('a').remove(); //Delete all tags A in the page
jQuery('a').remove('.ClassZ'); // Remove Class=ClassZ from any A tags

Replace Elements
jQuery('li.ClassZ').replaceWith('<li>removed</li>');

Copy Elements
jQuery('ul').clone().appendTo('body'); //copy ul tags add again to body
Add/Delete Attributes
Add Attribute
jQuery(document.body).attr('bgcolor')       // get bgcolor
jQuery('a').attr('href','http://www.jquery.com') //set new href to all a tags
jQuery('a').attr({'href':'http://www.jquery.com','title':'jquery.com'}).attr(‘class')

Since the class attribute can contain several values (e.g., class="class1 class2 class3"),
addClass()
hasClass()
removeClass()
toggleClass() //Adds the specified class if it is not present; removes the specified class if it is present



Remove Attribute
jQuery('a').removeAttr('title')
Adding/Get InnerHTML
jQuery('p').html('<strong>Hello </strong');
jQuery('p').html()
Looping Through a Set of Selected Results




                            $("ul > li:odd").addClass("odd");
                            $("ul > li:even").addClass(“even");
Attach Events
    <ul id="a">
    <li>list</li>
    <li>list</li>
    <li>list</li>
    <li>list</li>
    </ul>
    <ul id="b"></ul>

jQuery('ul#a li').click(function(){alert('List Item Clicked')});


jQuery("div").click(function() ,alert(“Div index "+ jQuery("div").index(this));})
jQuery('div').click(function(e){
                                alert('event');
                               })
             .keydown(function(e){
                                alert('event');
                              });
Events Binding
function buttonClicked(e){
          jQuery('div.panel').hide();
          jQuery('#panel'+e.data.panel).show();
          jQuery('#desc').text('You clicked the '+e.data.color+' button');
}
jQuery('#button1').bind('click',{panel:1, color:'red'}, buttonClicked);
jQuery('#button2').bind('click',{panel:2, color:'blue'}, buttonClicked);
jQuery('#button3').bind('click',{panel:3, color:'green'}, buttonClicked);
Form Validation
initializing the validation of the form using the validate() function.



The two parameters we used are:
rules: allows you to specify which fields you want to validate. In this case, we are validating name, email, url
     and comment. For each field, we specify if the field is required (required: true). We can specify that it must
     be a valid e-mail address, URL, etc.
messages: allows you to specify the error message for a particular field (like the comments field in the example
     above). If you don't specify it, a default message is provided that says "this field is required".



Validation methods
•    remote: requests a resource to check the element for validity.
•    min: makes the element require a given minimum.
•    date: makes the element require a date.
•    creditcard: makes the element require a credit card number.
•    equalTo: requires the element to be the same as another one.
<script src="jquery-latest.js"></script>
<script src="jquery.validate.js"></script>

 <script type="text/javascript">
  $(document).ready(function() {
   $("#form1").validate({
                   rules: {
                                   date1: true ,
                                   email1: {required: true,email: true },
                                   url1: {url: true},
                                   comment1: {required: true}
                          },
              messages:        {
                                   email1: { required: "We need your email ", email: "format Err" }
                                   comment1: "Please enter a comment."
                               }
   });
  });
 </script>

<form id="form1" method="post" action="">
    <input type="text" name="date1" />
    <input type="text" name="email1" />
    <input type="text" name="url1" />
    <textarea name="comment1" ></textarea>
    <input class="submit" type="submit" value="Submit">
</form>
Django
Create Project and Application
bash-3.00$ python django-admin.py startproject ProjectName
     command creates the following files:
     – __init__.py is an empty file that tells Python that the website directory should be treated as a
        Python package.
     – manage.py is the command-line utility that allows the administrator to start and manage the
        Django project.
     – settings.py configuration file of the Django project (Need DB to manage internal Process).
     – urls.py is a Python file that defines the syntax and configures the behavior of the URLs that
        will be used to access the website.
     Then Edit settings.py File for DB conn

            DATABASE_ENGINE = 'mysql'       # 'sqlite3' or 'oracle'.
            DATABASE_NAME = 'test'       # Or path to database file if using sqlite3.
            DATABASE_USER = 'root'      # Not used with sqlite3.
            DATABASE_PASSWORD = 'muhammad'
            DATABASE_HOST = ‘192.168.200.95'          # Set to empty string for localhost.
            DATABASE_PORT = ''      # Set to empty string for default.

bash-3.00$ python manage.py runserver
bash-3.00$ python manage.py syncdb

You can now visit the default server home page at http://127.0.0.1:8000
Create Your First Application
bash-3.00$ python manage.py startapp eulcProj1
    command creates the following files:
   – __init__.py website directory should be treated as a Python package.
   – models.py code for model classes
   – views.py    code for views


Reedit Setting.py add new project name to the list
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
' ProjectName.eulcProj1'
)
Django Has built in ORM
OPEN models.py file

from django.db import models
class Person(models.Model):
   name = models.CharField('name', max_length=200)
   text = models.TextField('Desc', max_length=500, blank=True)

   def __str__(self): return '%s' % (self.name)



Then call python manage.py syncdb to create the table in DB
Test DB Using commad line
python manage.py shell
from ProjectName.eulcProj1.models import Person
p = Person(name="your name", email="your eMail")
p.save()

More Related Content

What's hot

Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
Fabrizio Giudici
 

What's hot (20)

Magic of Ruby
Magic of RubyMagic of Ruby
Magic of Ruby
 
Scaling Databases with DBIx::Router
Scaling Databases with DBIx::RouterScaling Databases with DBIx::Router
Scaling Databases with DBIx::Router
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)Windows 8 JavaScript (Wonderland)
Windows 8 JavaScript (Wonderland)
 
Data normalization &amp; memoized denormalization
Data normalization &amp; memoized denormalizationData normalization &amp; memoized denormalization
Data normalization &amp; memoized denormalization
 
Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling Intro to MongoDB and datamodeling
Intro to MongoDB and datamodeling
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 
jQuery
jQueryjQuery
jQuery
 
Web2py
Web2pyWeb2py
Web2py
 
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
Recent Changes to jQuery's Internals
Recent Changes to jQuery's InternalsRecent Changes to jQuery's Internals
Recent Changes to jQuery's Internals
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applications
 
Introduction to jOOQ
Introduction to jOOQIntroduction to jOOQ
Introduction to jOOQ
 
Selectors and normalizing state shape
Selectors and normalizing state shapeSelectors and normalizing state shape
Selectors and normalizing state shape
 
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant   SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
 

Viewers also liked

Viewers also liked (11)

Python Comparing ORM
Python Comparing ORMPython Comparing ORM
Python Comparing ORM
 
Bootstarp 3
Bootstarp 3Bootstarp 3
Bootstarp 3
 
Extend IBM Enterprise Content Management Solutions with Content Navigator
Extend IBM Enterprise Content Management Solutions with Content NavigatorExtend IBM Enterprise Content Management Solutions with Content Navigator
Extend IBM Enterprise Content Management Solutions with Content Navigator
 
IBM Case Foundation Overview
IBM Case Foundation OverviewIBM Case Foundation Overview
IBM Case Foundation Overview
 
IBM Business Process Management 8.5
IBM Business Process Management 8.5IBM Business Process Management 8.5
IBM Business Process Management 8.5
 
IBM File Net P8
IBM File Net P8IBM File Net P8
IBM File Net P8
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Basic DBMS ppt
Basic DBMS pptBasic DBMS ppt
Basic DBMS ppt
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to Django - sql alchemy - jquery

Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
e-Legion
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
pauldix
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 

Similar to Django - sql alchemy - jquery (20)

The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189The Ring programming language version 1.6 book - Part 46 of 189
The Ring programming language version 1.6 book - Part 46 of 189
 
The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84The Ring programming language version 1.2 book - Part 32 of 84
The Ring programming language version 1.2 book - Part 32 of 84
 
Django (Web Konferencia 2009)
Django (Web Konferencia 2009)Django (Web Konferencia 2009)
Django (Web Konferencia 2009)
 
RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”
 
Where's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord MigrationsWhere's My SQL? Designing Databases with ActiveRecord Migrations
Where's My SQL? Designing Databases with ActiveRecord Migrations
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Building Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModelBuilding Web Service Clients with ActiveModel
Building Web Service Clients with ActiveModel
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184The Ring programming language version 1.5.3 book - Part 44 of 184
The Ring programming language version 1.5.3 book - Part 44 of 184
 

More from Mohammed El Rafie Tarabay (7)

التقنيات المستخدمة لتطوير المكتبات
التقنيات المستخدمة لتطوير المكتباتالتقنيات المستخدمة لتطوير المكتبات
التقنيات المستخدمة لتطوير المكتبات
 
R for Statistical Computing
R for Statistical ComputingR for Statistical Computing
R for Statistical Computing
 
IBM Business Automation Workflow
IBM Business Automation WorkflowIBM Business Automation Workflow
IBM Business Automation Workflow
 
Python crush course
Python crush coursePython crush course
Python crush course
 
Django crush course
Django crush course Django crush course
Django crush course
 
ITIL
ITILITIL
ITIL
 
React native
React nativeReact native
React native
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Django - sql alchemy - jquery

  • 1. Django - Sql Alchemy - JQuery Rafie Tarabay eng_rafie@mans.edu.eg
  • 2. Others Safary Chrome Firefox IE JQuery Oracle Sql Alchemy My Application MySql Django MSSql Google App Apache IIS Tornado Django Server
  • 3. SQL Alchemy To write SQL query compatible with all databases using ORM
  • 4. Creating Table, Class and Mapper from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = ’users’ id = Column(Integer, primary_key=True) name = Column(’f2’, String(50)) fullname = Column(’f3’, String(50)) password = Column(’f4’, String(50)) def __init__(self, name, fullname, password): self.name = name self.fullname = fullname self.password = password def __repr__(self): return "<User(’%s’,’%s’, ’%s’)>" % (self.name, self.fullname, self.password)
  • 5. Creating a Session to DB from sqlalchemy.orm import sessionmaker engine = create_engine(’sqlite:///:memory:’, echo=True) Session = sessionmaker(bind=engine) For Other DB Connections: • create_engine(’mysql://scott:tiger@localhost/foo’) • create_engine(’oracle://scott:tiger@127.0.0.1:1521/sidname’) • create_engine(’mssql://mydsn’) • create_engine(’sqlite:////absolute/path/to/foo.db’)
  • 6. Adding new Objects Add Row ed_user = User(’ed’, ’Ed Jones’, ’edspassword’) session.add(ed_user) Edit Row ed_user.password = ’f8s7ccs’ Add Batch session.add_all([ User(’wendy’, ’Wendy Williams’, ’foobar’), User(’mary’, ’Mary Contrary’, ’xxg527’), User(’fred’, ’Fred Flinstone’, ’blah’)+) Apply Changes session.commit() session.rollback()
  • 7. Query our_user = session.query(User).filter_by(name=’ed’).first() for name, in session.query(User.name).filter(User.fullname==’Ed Jones’): print name for user in session.query(User).filter(User.id>5).filter(User.fullname==’Ed’): print user for instance in session.query(User).order_by(User.id): print instance.name, instance.fullname Note You can control the names using the label() construct for scalar attributes and aliased() for class constructs: user_alias = aliased(User, name=’user_alias’) user_alias.name.label(’name_label’)
  • 8. Common Filter Operators equals: query.filter(User.name == ’ed’) not equals: query.filter(User.name != ’ed’) LIKE: query.filter(User.name.like(’%ed%’)) IN: query.filter(User.name.in_(*’ed’, ’wendy’+)) Nested SQL: query.filter(User.name.in_(session.query(User.name).filter(User.name.like(’%ed%’)))) NOT IN: query.filter(~User.name.in_(*’ed’, ’wendy’, ’jack’+)) IS NULL: filter(User.name == None) IS NOT NULL: filter(User.name != None) AND: from sqlalchemy import and_ filter(and_(User.name == ’ed’, User.fullname == ’Ed Jones’)) # or call filter()/filter_by() multiple times filter(User.name == ’ed’).filter(User.fullname == ’Ed OR: from sqlalchemy import or_ filter(or_(User.name == ’ed’, User.name == ’wendy’))
  • 9. Parameter session.query(User).filter("id<:value and name=:name"). params(value=224, name=’fred’).order_by(User.id).one() session.query(User).from_statement("SELECT * FROM users where name=:name").params(name=’asfasdf’) session.query("id", "name", "thenumber12") .from_statement("SELECT id, name, 12 as thenumber12 FROM users where name=:name").params(name='ed').all()
  • 11. Building a Relationship >>> from sqlalchemy import ForeignKey >>> from sqlalchemy.orm import relationship, backref >>> class Address(Base): ... __tablename__ = 'addresses' ... id = Column(Integer, primary_key=True) ... email_address = Column(String, nullable=False) ... user_id = Column(Integer, ForeignKey('users.id')) ... ... user = relationship(User, backref=backref('addresses', order_by=id)) ... ... def __init__(self, email_address): ... self.email_address = email_address ... ... def __repr__(self): ... return "<Address('%s')>" % self.email_address ================================================================================== class User(Base): # .... addresses = relationship(Address, order_by=Address.id, backref="user")
  • 12. Notes • The above class introduces a foreign key constraint which references the users table. This defines for SQLAlchemy the relationship between the two tables at the database level. • The relationship between the User and Address classes is defined separately using the relationship() function, which defines an attribute user to be placed on the Address class, as well as an addresses collection to be placed on the User class. Such a relationship is known as a bidirectional relationship. • We free to not define a backref, and to define the relationship() only on one class and not the other.
  • 13. Working with Related Objects • jack = User(’jack’, ’Jack Bean’, ’gjffdd’) • jack.addresses = [Address(email_address='jack@google.com'), Addr ess(email_address='j25@yahoo.com')]
  • 14. Another Method SQL EXPRESSION
  • 15. Connection from sqlalchemy import create_engine engine = create_engine(’sqlite:///:memory:’, echo=True) Create Table from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey metadata = MetaData() users = Table(’users’, metadata, Column(’id’, Integer, primary_key=True), Column(’name’, String), Column(’fullname’, String), ) addresses = Table(’addresses’, metadata, Column(’id’, Integer, primary_key=True), Column(’user_id’, None, ForeignKey(’users.id’)), Column(’email_address’, String, nullable=False) ) metadata.create_all(engine) Insert Data We Have 4 methods
  • 16. Method 1 conn = engine.connect() ins = users.insert().values(name=’jack’, fullname=’Jack Jones’) result = conn.execute(ins) result.inserted_primary_key Method 2 conn = engine.connect() conn.execute(addresses.insert(), [ ,’user_id’: 1, ’email_address’ : ’jack@yahoo.com’-, ,’user_id’: 1, ’email_address’ : ’jack@msn.com’-, ,’user_id’: 2, ’email_address’ : ’www@www.org’-, ,’user_id’: 2, ’email_address’ : ’wendy@aol.com’-, ]) Method 3 result = engine.execute(users.insert(), name=’fred’, fullname=“Flintstone") Method 4 metadata.bind = engine result = users.insert().execute(name="mary", fullname="Mary Contrary")
  • 18. Connection /Connectionless We’re executing our Insert using a Connection (Method1,2). Or allow you to not have to deal with the connection part. You can execute in the connectionless style, using the engine, which opens and closes a connection for you (Method 3,4)
  • 19. Query Ex1 sql = select([users, addresses], users.c.id==addresses.c.user_id) for row in conn.execute(sql): print row Ex2 s = select([(users.c.fullname + ", " + addresses.c.email_address).label(’title’)+, and_( users.c.id==addresses.c.user_id, users.c.name.between(’m’, ’z’), or_( addresses.c.email_address.like(’%@aol.com’), addresses.c.email_address.like(’%@msn.com’) ) ) ) print conn.execute(s).fetchall()
  • 20. Normal Query from sqlalchemy.sql import text s = text(""“ SELECT users.fullname || ’, ’ || addresses.email_address AS title FROM users, addresses WHERE users.id = addresses.user_id AND users.name BETWEEN :x AND :y AND (addresses.email_address LIKE :e1 OR addresses.email_address LIKE :e2) """) print conn.execute(s, x=’m’, y=’z’, e1=’%@aol.com’, e2=’%@msn.com’).fetchall() hybrid approach s = select(["users.fullname || ’, ’ || addresses.email_address AS title"], and_( "users.id = addresses.user_id", "users.name BETWEEN ’m’ AND ’z’", "(addresses.email_address LIKE :x OR addresses.email_address LIKE :y)" ), from_obj=*’users’, ’addresses’+ ) print conn.execute(s, x=’%@aol.com’, y=’%@msn.com’).fetchall()
  • 21. Transaction # method_a starts a transaction and calls method_b def method_a(connection): trans = connection.begin() # open a transaction try: method_b(connection) trans.commit() # transaction is committed here except: trans.rollback() # this rolls back the transaction unconditionally Raise # method_b also starts a transaction def method_b(connection): trans = connection.begin() # open a transaction - this runs in the context of method_a’s try: connection.execute("insert into mytable values (’bat’, ’lala’)") connection.execute(mytable.insert(), col1=’bat’, col2=’lala’) trans.commit() # transaction is not committed yet except: trans.rollback() # this rolls back the transaction unconditionally Raise # open a Connection and call method_a conn = engine.connect() method_a(conn)
  • 22. JQuery To write JavaScript Compatible with all web browsers
  • 23. Compare onLoad & Ready window.onload : work only if all page +Images+Swf loaded Solution <script type="text/JavaScript"> jQuery(document).ready(function() { alert(‘All TextPage Loaded’); } ); </script>
  • 24. Select Element <script type="text/JavaScript” src=“jquery.min.js"></script> <a href="/category">Category</a> <ul id="nav“ class=“ClassZ”> <li><a href="#anchor1">Anchor 1</a></li> <li><a href="#anchor2">Anchor 2</a></li> <li><span><a href="#anchor3">Anchor 3</a></span></li> </ul> jQuery('#nav’) jQuery('#nav li > a'); // This selects two elements, as expected jQuery('#content span a'); // all anchor within all span elements within #content jQuery(‘.ClassZ'); // Select elelments with calss= classZ jQuery('li:eq(1)'); //selects the second element in the set of <li>'s by index, index starts at 0
  • 25. Attributes Help In Selections :first Matches the first selected element :last Matches the last selected element :even Matches even elements (zero-indexed) :odd Matches odd elements (zero-indexed) :eq(n) Matches a single element by its index (n) :lt(n) Matches all elements with index below n :gt(n) Matches all elements with index above n
  • 26. Selecting Elements Based on What They Contain <span>Hello Bob!</span> // Select all SPANs with 'Bob' in: jQuery('span:contains("Bob")'); //it’s case sensitive jQuery('div:not(#content)'); // Select all DIV elements except #content To test for nested elements, you can use the :has() filter. jQuery('div:has(p a)');
  • 27. Selecting Elements Based on Their Visibility jQuery('div:hidden'); jQuery('p:visible').hide(); // Hiding only elements that are currently visible if (jQuery('#elem').is(':hidden')) { // Do something conditionally }
  • 28. Selecting Form Elements by Type :text <input type="text" /> :password <input type="password" /> :radio <input type="radio" /> :checkbox <input type="checkbox" /> :submit <input type="submit" /> :image <input type="image" /> :reset <input type="reset" /> :button <input type="button" /> :file <input type="file" /> :hidden <input type="hidden" /> jQuery(':text'); //select all text inputs, jQuery(':input:not(:hidden)'); // Selects all input elements not hidden.
  • 29. Navigate in DOM jQuery('li:eq(1)').next() //selects the third <li> jQuery('li:eq(1)').prev() //selects the first <li> jQuery('li:eq(1)').parent() //selects the <ul> jQuery('li:eq(1)').nextAll() //selects all the <li>s after the second <li> jQuery('li:eq(1)').prevAll() //selects all the <li>s before the second <li> jQuery('li:eq(1)').parent().children() //selects all <li>s jQuery('li:eq(1)').parent().children(':last') //selects the last <li>
  • 30. Apply Effect on Selected Elements jQuery('div'). css('border','1px solid #993300'); //add a class attribute with a value of updatedContent to all divs jQuery('div')[0].addClass("updatedContent"); //hide all divs on the page jQuery('div').hide(); //update the text contained inside of all divs jQuery('div').text('new content'); //show all divs on the page jQuery('div').show(); jQuery('a').length jQuery('input',$('form')).length jQuery('input','body').length jQuery('input',document.forms[0]).length jQuery('#username').focus(); //<input name="username" id="username" type="text" /> jQuery('#username'). val();
  • 31. <style> table tr.even {background: #CCC;} <style> <table> <tr><td>0</td><td>even</td></tr> <tr><td>1</td><td>odd</td></tr> <tr><td>2</td><td>even</td></tr> <tr><td>3</td><td>odd</td></tr> <tr><td>4</td><td>even</td></tr> </table> jQuery('tr:even').addClass('even');
  • 32. Inject DOM/Remove/Replacing/Copy Inject Elements appendTo() Example jQuery('<p><a>jQuery</a></p>'). appendTo('body'); insertAfter() insertBefore() Remove Element jQuery('a').remove(); //Delete all tags A in the page jQuery('a').remove('.ClassZ'); // Remove Class=ClassZ from any A tags Replace Elements jQuery('li.ClassZ').replaceWith('<li>removed</li>'); Copy Elements jQuery('ul').clone().appendTo('body'); //copy ul tags add again to body
  • 33. Add/Delete Attributes Add Attribute jQuery(document.body).attr('bgcolor') // get bgcolor jQuery('a').attr('href','http://www.jquery.com') //set new href to all a tags jQuery('a').attr({'href':'http://www.jquery.com','title':'jquery.com'}).attr(‘class') Since the class attribute can contain several values (e.g., class="class1 class2 class3"), addClass() hasClass() removeClass() toggleClass() //Adds the specified class if it is not present; removes the specified class if it is present Remove Attribute jQuery('a').removeAttr('title')
  • 35. Looping Through a Set of Selected Results $("ul > li:odd").addClass("odd"); $("ul > li:even").addClass(“even");
  • 36. Attach Events <ul id="a"> <li>list</li> <li>list</li> <li>list</li> <li>list</li> </ul> <ul id="b"></ul> jQuery('ul#a li').click(function(){alert('List Item Clicked')}); jQuery("div").click(function() ,alert(“Div index "+ jQuery("div").index(this));})
  • 37. jQuery('div').click(function(e){ alert('event'); }) .keydown(function(e){ alert('event'); });
  • 38. Events Binding function buttonClicked(e){ jQuery('div.panel').hide(); jQuery('#panel'+e.data.panel).show(); jQuery('#desc').text('You clicked the '+e.data.color+' button'); } jQuery('#button1').bind('click',{panel:1, color:'red'}, buttonClicked); jQuery('#button2').bind('click',{panel:2, color:'blue'}, buttonClicked); jQuery('#button3').bind('click',{panel:3, color:'green'}, buttonClicked);
  • 39. Form Validation initializing the validation of the form using the validate() function. The two parameters we used are: rules: allows you to specify which fields you want to validate. In this case, we are validating name, email, url and comment. For each field, we specify if the field is required (required: true). We can specify that it must be a valid e-mail address, URL, etc. messages: allows you to specify the error message for a particular field (like the comments field in the example above). If you don't specify it, a default message is provided that says "this field is required". Validation methods • remote: requests a resource to check the element for validity. • min: makes the element require a given minimum. • date: makes the element require a date. • creditcard: makes the element require a credit card number. • equalTo: requires the element to be the same as another one.
  • 40. <script src="jquery-latest.js"></script> <script src="jquery.validate.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#form1").validate({ rules: { date1: true , email1: {required: true,email: true }, url1: {url: true}, comment1: {required: true} }, messages: { email1: { required: "We need your email ", email: "format Err" } comment1: "Please enter a comment." } }); }); </script> <form id="form1" method="post" action=""> <input type="text" name="date1" /> <input type="text" name="email1" /> <input type="text" name="url1" /> <textarea name="comment1" ></textarea> <input class="submit" type="submit" value="Submit"> </form>
  • 42. Create Project and Application bash-3.00$ python django-admin.py startproject ProjectName command creates the following files: – __init__.py is an empty file that tells Python that the website directory should be treated as a Python package. – manage.py is the command-line utility that allows the administrator to start and manage the Django project. – settings.py configuration file of the Django project (Need DB to manage internal Process). – urls.py is a Python file that defines the syntax and configures the behavior of the URLs that will be used to access the website. Then Edit settings.py File for DB conn DATABASE_ENGINE = 'mysql' # 'sqlite3' or 'oracle'. DATABASE_NAME = 'test' # Or path to database file if using sqlite3. DATABASE_USER = 'root' # Not used with sqlite3. DATABASE_PASSWORD = 'muhammad' DATABASE_HOST = ‘192.168.200.95' # Set to empty string for localhost. DATABASE_PORT = '' # Set to empty string for default. bash-3.00$ python manage.py runserver bash-3.00$ python manage.py syncdb You can now visit the default server home page at http://127.0.0.1:8000
  • 43. Create Your First Application bash-3.00$ python manage.py startapp eulcProj1 command creates the following files: – __init__.py website directory should be treated as a Python package. – models.py code for model classes – views.py code for views Reedit Setting.py add new project name to the list INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', ' ProjectName.eulcProj1' )
  • 44. Django Has built in ORM OPEN models.py file from django.db import models class Person(models.Model): name = models.CharField('name', max_length=200) text = models.TextField('Desc', max_length=500, blank=True) def __str__(self): return '%s' % (self.name) Then call python manage.py syncdb to create the table in DB
  • 45. Test DB Using commad line python manage.py shell from ProjectName.eulcProj1.models import Person p = Person(name="your name", email="your eMail") p.save()