Monday, June 14, 2010

Dictionaries — Groupings of Data Indexed by Name


A dictionary is similar to lists and tuples. It’s another type of container for a group of data. However,
whereas tuples and lists are indexed by their numeric order, dictionaries are indexed by names that you
choose. These names can be letters, numbers strings, or symbols — whatever suits you.

Making a Dictionary
Dictionaries are created using the curly braces. To start with, you can create the simplest dictionary,
which is an empty dictionary, and populate it using names and values that you specify one per line:
    >>>  menus_specials = {}
    >>>  menus_specials[“breakfast”] = “canadian ham”
    >>>  menus_specials[“lunch”] = “tuna surprise”
    >>>  menus_specials[“dinner”] = “Cheeseburger Deluxe”

for example :-
>>> menu_specials = {“breakfast” : “sausage and eggs”,
...     “lunch” : “split pea soup and garlic bread”,
...     “dinner”: “2 hot dogs and onion rings”}

>>> print “%s” % menu_specials[“breakfast”]
sausage and eggs
>>> print “%s” % menu_specials[“lunch”]
split pea soup and garlic bread
>>> print “%s” % menu_specials[“dinner”]
2 hot dogs and onion rings

Getting the Keys from a Dictionary
Dictionaries can tell you what all of their keys are, or what all of their values are, if you know how to ask
them. The keys method will ask the dictionary to return all of its keys to you as a list so that you can
examine them for the key (or keys) you are looking for, and the values method will return all of the val-
ues as a list.
    >>> menu_specials.keys()
    [‘lunch’, ‘breakfast’, ‘dinner’]
    >>> menu_specials.values()
    [‘split pea soup and garlic bread’, ‘sausage and eggs’, ‘2 hot dogs and onion
    rings’]

One other thing to note about a dictionary is that you can ask the list whether a particular key already
exists. You can use a special built-in method called __contains__, which will return True or False.
When you invoke a method like __contains__, you are asking a question of it, and it will answer with
its version of yes, which is True or no, which is False.
>>> menu_specials.__contains__(“midnight specials”)
False
>>> menu_specials.__contains__(“Lunch”)
False
>>> menu_specials.__contains__(“lunch”)
True

Sunday, June 13, 2010

Variables — Names for Values

 Assigning Values to Names

These names are commonly called variables, which indicates that the data to which they refer can vary
(it can be changed), while the name remains the same. You’ll see them referred to as names, as well,
because that is what you are presented with by Python.
     >>> first_string = “This is a string”
     >>> second_string = “This is another string”
     >>> first_number = 4
     >>> second_number = 5
     >>> print “The first variables are %s, %s, %d, %d” % (first_string, second_string,
     first_number, second_number)
     The first variables are This is a string, This is another string, 4, 5


Altering Named Values
Every operation you’ve learned for numbers and strings can be used with a variable name so that you
can treat them exactly as if they were the numbers they referenced:
    >>> proverb = “A penny saved”
    >>> proverb = proverb + “ is a penny earned”
    >>> print proverb
    A penny saved is a penny earned

Names You Can’t Use and Some Rules
 Python uses a few names as special built-in words that it reserves for special use to prevent ambiguity.
 The following words are reserved by Python and can’t be used as the names for data:
     and, assert, break, class, continue, def, del, elif, else, except, exec, finally,
     for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return,
     try, while, yield

Using stings And numbers in Python


Starting codeEditor
  Depending on your operating system, you will start codeEditor in different ways.
  Once it is installed on your system with Python, on Linux or Unix-based systems, you can just type python in a terminal or shell window and it will start.

Using string in python 

>>> “This text really won’t do anything”
“This text really won’t do anything”
>>> ‘This is also a string’
‘This is also a string’
>>> “””This is a third string that is some
   ...      how different”””
‘This is a third string that is some\n     how different’
>>> ‘And he said \’this string has escaped quotes\’’
“And he said ‘this string has escaped quotes’”

//Using + to Combine Strings
>>> “John” + “Q.” + “Public”
‘JohnQ.Public’
>>> “John” + “ “ + “Q.” + “ “ + “Public”
‘John Q. Public’
//Using a Format Specifier to Populate a String
//In the simplest case, you can do the same thing with your friend, John Q.:
>>> “John Q. %s” % (“Public”)
    ‘John Q. Public’
//More String Formatting
//You can do a couple of useful things when formatting a simple string:
>>> “%s %s %10s” % (“John”, “Q.”, “Public”)
   ‘John Q.        Public’
>>> “%-10s %s %10s” % (“John”, “Q.”, “Public”)
   ‘John         Q.       Public’

Numbers in Python
Python offers four different kinds of numbers with which you can work: integers, long numbers
 (or longs), floating-point numbers (or floats), and imaginary numbers.

>>> type(1)
<type ‘int’>
>>> type(2000)
<type ‘int’>
>>> type(999999999999)
<type ‘long’>
>>> type(1.0)
<type ‘float’>

Creating an Imaginary Number
The imaginary number behaves very much like a float, except that it cannot be mixed with a float. When
you see an imaginary number, it will have the letter j trailing it:
    >>> 12j
    12j

You can combine imaginary and nonimaginary numbers to create complex numbers:
   >>> 12j + 1
   (1+12j)
   >>> 12j + 1.01
   (1.01+12j)
   >>> type (12j + 1)
   <type ‘complex’>

Including Different Numbers in Strings
When you combined two strings in the first chapter by using a format specifier, you used the format
specifier %s, which means “a string.” Because numbers and strings have different types, you will use a
different specifier that will enable your numbers to be included in a string:
     >>> “Including an integer works with %%d like this: %d” % 10
     ‘Including an integer works with %d like this: 10’
     >>> “An integer converted to a float with %%f: %f” % 5
     ‘An integer converted to a float with %f: 5.000000’
     >>> “A normal float with %%f: %f” % 1.2345
     ‘A normal float with %f: 1.234500’
     >>> “A really large number with %%E: %E” % 6.789E10
     ‘A really large number with %E: 6.789000E+10’
     >>> “Controlling the number of decimal places shown: %.02f” % 25.101010101
     ‘Controlling the number of decimal places shown: 25.10’

  Escaping the % Sign in Strings
One other trick was shown before. In case you wanted to print the literal string %d in your program, you
achieve that in Python strings by using two % signs together. This is needed only when you also have
valid format specifiers that you want Python to substitute for you in the same string:
    print “The %% behaves differently when combined with other letters, like this: %%d
    %%s %%f %d” % 10
    The % behaves differently when combined with other letters, like this: %d %s %f 10

Doing Basic Math
You can enter basic arithmetic at the Python shell prompt and use it like a calculator. Like a calculator,
Python will accept a set of operations, and when you hit the Enter key, it will evaluate everything you’ve
typed and give you your answer:
    >>> 5 + 300
    305
    >>> 399 + 3020 + 1 + 3456
    6876
    >>> 300 - 59994 + 20
    -59674
    >>> 4023 - 22.46
    4000.54
>>> 2000403030 * 392381727
784921595607432810L
>>> 2000403030 * 3923817273929
7849215963933911604870L
>>> 2e304 * 3923817273929
inf
>>> 2e34 * 3923817273929
7.8476345478579995e+46
>>> 44 / 11
4
>>> 324 / 101
3
>>> 324.0 / 101.0
3.2079207920792081
>>> 324.0 / 101
3.2079207920792081
>>> 5 % 3
2

Printing the Results
Try actually printing the results, so that the preceding math with the unusual-looking results has its
results displayed to a user, as it would from inside of a program:
    >>> print “%f” % (4023 - 22.4)
    4000.600000
Using Math Operations
When you’re thinking about a particular set of mathematical operations, it can seem straightforward
when you write it down (or type it in). When you look at it later, however, it can become confusing. Try
these examples, and imagine them without the parentheses:
    >>> (24 * 8)
    192
    >>> (24 * (8 + 3))
    264
    >>> (24 * (8 + 3 + 7.0))
    432.0
   
Using Number Formats
Try this, for example. Here, you print a number as though you were printing a dollar amount:
    >>> print “$%.02f” % 30.0
    $30.00





Problem with Django admin

i am using  Django Version: 1.2.1
I follow this Tutorial  http://docs.djangoproject.com/en/1.2/intro/tutorial01/
and
Edit the polls/models.py  file so it looks like this:

class Poll(models.Model):
    # ...
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    # ...
    def __unicode__(self):
        return self.choice

After doing that  i run this command :

python manage.py shell

this error is come
Validating models...
Unhandled exception in thread started by <function inner_run at
0x9c574fc>
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/
commands/runserver.py", line 48, in inner_run
    self.validate(display_num_errors=True)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/
base.py", line 245, in validate
    num_errors = get_validation_errors(s, app)
  File "/usr/local/lib/python2.6/dist-packages/django/core/management/
validation.py", line 28, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/
loading.py", line 146, in get_app_errors
    self._populate()
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/
loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/
loading.py", line 78, in load_app
    models = import_module('.models', app_name)
  File "/usr/local/lib/python2.6/dist-packages/django/utils/
importlib.py", line 35, in import_module
    __import__(name)
  File "/home/jagdeep/mysite/../mysite/polls/models.py", line 19
    def __unicode__(self):
                         ^
IndentationError: unindent does not match any outer indentation level

I submit my problem on :-
django-users+noreply@googlegroups.com 
.
then the Django user  reply back and problem solved
I Check my indentation of that particular line, and all of the lines
above. In Python, indentation matters, and it all needs to line up
accordingly.

Now my django admin is work.

Thursday, June 10, 2010

Creating models in Django

Now that your environment -- a "project" -- is set up, you're set to start doing work.
Each application you write in Django consists of a Python package, somewhere on your Python path, that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.

In this tutorial, we'll create our poll app in the mysite directory, for simplicity. As a consequence, the app will be coupled to the project -- that is, Python code within the poll app will refer to mysite.polls. Later in this tutorial, we'll discuss decoupling your apps for distribution.
To create your app, make sure you're in the mysite directory and type this command:
python manage.py startapp polls

That'll create a directory polls, which is laid out like this:
polls/
    __init__.py
    models.py
    tests.py
    views.py
This directory structure will house the poll application.

In our simple poll app, we'll create two models: polls and choices. A poll has a question and a publication date. A choice has two fields: the text of the choice and a vote tally. Each choice is associated with a poll.
These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks like this:
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField
 

Activating models

That small bit of model code gives Django a lot of information. With it, Django is able to:
  • Create a database schema (CREATE TABLE statements) for this app.
  • Create a Python database-access API for accessing Poll and Choice objects.
But first we need to tell our project that the polls app is installed.

Edit the settings.py file again, and change the INSTALLED_APPS setting to include the string 'mysite.polls'. So it'll look like this:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'mysite.polls'
)
Now Django knows mysite includes the polls app. Let's run another command:
python manage.py sql polls
You should see something similar to the following (the CREATE TABLE SQL statements for the polls app):
BEGIN;
CREATE TABLE "polls_poll" (
    "id" serial NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);
CREATE TABLE "polls_choice" (
    "id" serial NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
COMMIT;


If you're interested, 
also run the following commands:
Looking at the output of those commands can help you understand what's actually happening under the hood.
Now, run syncdb again to create those model tables in your database:
python manage.py syncdb
The syncdb command runs the sql from 'sqlall' on your database for all apps in INSTALLED_APPS that don't already exist in your database. This creates all the tables, initial data and indexes for any apps you have added to your project since the last time you ran syncdb. syncdb can be called as often as you like, and it will only ever create the tables that don't exist.
Read the django-admin.py documentation for full information on what the manage.py utility can do.

Playing with the API

Now, let's hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:
python manage.py shell
We're using this instead of simply typing "python", because manage.py sets up the project's environment for you. "Setting up the environment" involves two things:


  • Putting mysite on sys.path. For flexibility, several pieces of Django refer to projects in Python dotted-path notation (e.g. 'mysite.polls.models'). In order for this to work, the mysite package has to be on sys.path.
    We've already seen one example of this: the INSTALLED_APPS setting is a list of packages in dotted-path notation.


  • Setting the DJANGO_SETTINGS_MODULE environment variable, which gives Django the path to your settings.py file.
    nce you're in the shell, explore the database API:
    >>> from mysite.polls.models import Poll, Choice  
    # Import the model classes we just wrote.
    
    # No polls are in the system yet.
    >>> Poll.objects.all()
    []
    
    # Create a new Poll.
    >>> import datetime
    >>> p=Poll(question="What's up?",pub_date=datetime.datetime.now())
    
    # Save the object into the database. You have to call save() 
      explicitly.
    >>> p.save()
    
    # Now it has an ID. Note that this might say "1L" 
    instead of "1", depending
    # on which database you're using. That's no biggie; 
    it just means your
    # database backend prefers to return integers as 
    Python long integer
    # objects.
    >>> p.id
    1
    
    # Access database columns via Python attributes.
    >>> p.question
    "What's up?"
    >>> p.pub_date
    datetime.datetime(2007, 7, 15, 12, 00, 53)
    
    # Change values by changing the attributes, then calling save().
    >>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
    >>> p.save()
    
    # objects.all() displays all the polls in the database.
    >>> Poll.objects.all()
    [<Poll: Poll object>]
Wait a minute. <Poll: Poll object> is, utterly, an unhelpful representation of this object. Let’s fix that by editing the polls model (in the polls/models.py file) and adding a __str__() method to both Poll and Choice:
class Poll(models.Model):
    # ...
    def __str__(self):
        return self.question

class Choice(models.Model):
    # ...
    def __str__(self):
        return self.choice

It’s important to add __str__() methods to your models, not only for your own sanity when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.
Note these are normal Python methods. Let’s add a custom method, just for demonstration:
import datetime
# ...
class Poll(models.Model):
    # ...
    def was_published_today(self):
        return self.pub_date.date() == datetime.date.today()

Note the addition of import datetime to reference Python’s standard datetime module.
Let’s jump back into the Python interactive shell by running python manage.py shell again:
>>> from mysite.polls.models import Poll, Choice

# Make sure our __str__() addition worked.
>>> Poll.objects.all()
[<Poll: What's up?>]

# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Poll.objects.filter(id=1)
[<Poll: What's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: What's up?>]

# Get the poll whose year is 2005. Of course, if you're 
going through this
# tutorial in another year, change as appropriate.
>>> Poll.objects.get(pub_date__year=2005)
<Poll: What's up?>

>>> Poll.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Poll matching query does not exist.

# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Poll.objects.get(id=1).
>>> Poll.objects.get(pk=1)
<Poll: What's up?>

# Make sure our custom method worked.
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_today()
False

# Give the Poll a couple of Choices. The create call constructs a new
# choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object.
>>> p = Poll.objects.get(pk=1)
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)

# Choice objects have API access to their related Poll objects.
>>> c.poll
<Poll: What's up?>

# And vice versa: Poll objects get access to Choice objects.
>>> p.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> p.choice_set.count()
3

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want. There's no limit.
# Find all Choices for any poll whose pub_date is in 2005.
>>> Choice.objects.filter(poll__pub_date__year=2005)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

# Let's delete one of the choices. Use delete() for that.
>>> c = p.choice_set.filter(choice_startswith='Just hacking')
>>> c.delete()