http://www.django-cms.org/
http://pinaxproject.com/
About Pinax
Pinax
is an open-source platform built on the Django Web Framework.
By
integrating numerous reusable Django apps to take care of the
things that many sites have in common, it lets you focus on what
makes
your site different.
Tuesday, June 29, 2010
Thursday, June 24, 2010
Change the date — Format of PHP according to requirement
Php have inbuilt function date ( fromat , strtotime($date) )
for example :
$date = '11877962147'
$date =date('d-m-y' ,strtotime($date));
echo $date;
format :-
$date = '11877962147'
$date =date('d-m-y' ,strtotime($date));
echo $date;
format character | Description | Example returned values |
---|---|---|
Day | --- | --- |
d | Day of the month, 2 digits with leading zeros | 01 to 31 |
D | A textual representation of a day, three letters | Mon through Sun |
j | Day of the month without leading zeros | 1 to 31 |
l (lowercase 'L') | A full textual representation of the day of the week | Sunday through Saturday |
N | ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday) |
S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j |
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
z | The day of the year (starting from 0) | 0 through 365 |
Week | --- | --- |
W | ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) | Example: 42 (the 42nd week in the year) |
Month | --- | --- |
F | A full textual representation of a month, such as January or March | January through December |
m | Numeric representation of a month, with leading zeros | 01 through 12 |
M | A short textual representation of a month, three letters | Jan through Dec |
n | Numeric representation of a month, without leading zeros | 1 through 12 |
t | Number of days in the given month | 28 through 31 |
Year | --- | --- |
L | Whether it's a leap year | 1 if it is a leap year, 0 otherwise. |
o | ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) | Examples: 1999 or 2003 |
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
y | A two digit representation of a year | Examples: 99 or 03 |
Time | --- | --- |
a | Lowercase Ante meridiem and Post meridiem | am or pm |
A | Uppercase Ante meridiem and Post meridiem | AM or PM |
B | Swatch Internet time | 000 through 999 |
g | 12-hour format of an hour without leading zeros | 1 through 12 |
G | 24-hour format of an hour without leading zeros | 0 through 23 |
h | 12-hour format of an hour with leading zeros | 01 through 12 |
H | 24-hour format of an hour with leading zeros | 00 through 23 |
i | Minutes with leading zeros | 00 to 59 |
s | Seconds, with leading zeros | 00 through 59 |
u | Microseconds (added in PHP 5.2.2) | Example: 654321 |
Timezone | --- | --- |
e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores |
I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise. |
O | Difference to Greenwich time (GMT) in hours | Example: +0200 |
P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00 |
T | Timezone abbreviation | Examples: EST, MDT ... |
Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400 |
Full Date/Time | --- | --- |
c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00 |
r | formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200 |
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Also use time() |
Monday, June 21, 2010
Serving media files in Django
Serving media files
Django doesn't serve media files itself; it leaves that job to whichever Web server you choose.We recommend using a separate Web server -- i.e., one that's not also running Django -- for serving media. Here are some good choices:
If, however, you have no option but to serve media files on the same Apache VirtualHost as Django, you can set up Apache to serve some URLs as static media, and others using the mod_wsgi interface to Django.
This example sets up Django at the site root, but explicitly serves robots.txt, favicon.ico, any CSS file, and anything in the /media/ URL space as a static file. All other URLs will be served using mod_wsgi:
Alias /media/ /usr/local/wsgi/static/media/
<Directory /usr/local/wsgi/static>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /usr/local/wsgi/scripts/django.wsgi
<Directory /usr/local/wsgi/scripts>
Order allow,deny
Allow from all
</Directory>
More details on configuring a mod_wsgi site to serve static files can be found in the mod_wsgi documentation on hosting static files.
Problem : -
Myhttp://localhost/admin/ is display in pattern without grapic or image not like that which is shown in Tutorial
http://docs.djangoproject.com/en/1.2/intro/tutorial02/#intro-tutorial02
MY admin page (http://localhost/admin/)
Django administration
Welcome, Jagdeep. Change password / Log out
Site administration
Auth
Groups Add Change
Users Add Change
Polls
Polls Add Change
Sites
Sites Add Change
Recent Actions
Welcome, Jagdeep. Change password / Log out
Site administration
Auth
Groups Add Change
Users Add Change
Polls
Polls Add Change
Sites
Sites Add Change
My Actions
where is the problem .........i am not able to find???
After a Long discussion on django-user mailing list i am able to find the solution
Solution :-
Major problem is giving the path wrong path of media directory.
httpd.conf apacha file editing
Alias /media/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/
<Directory /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/>
Options Indexes
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /home/jagdeep/mysite/apache/django.wsgi
<Directory /home/jagdeep/mysite/apache/>
Order allow,deny
Allow from all
</Directory>
and after this set the default setting of setting.py file of django .
Wednesday, June 16, 2010
Modules used in Python
A module looks much like your normal python program.
We import bits of it (or all of it) into other programs.
To import all the variables, functions and classes from file1.py into another program you are writing, we use the import operator. For example, to import file2.py into your main program, you would have this:
Code Example
We import bits of it (or all of it) into other programs.
To import all the variables, functions and classes from file1.py into another program you are writing, we use the import operator. For example, to import file2.py into your main program, you would have this:
Code Example
### mainprogam.py ### IMPORTS ANOTHER MODULE import moduletname
continue ..........
......
......
More module thingummyjigs (in lack of a better title)
Wish you could get rid of the modulename. part that you have to put before every item you use from a module? No? Never? Well, I'll teach it you anyway. One way to avoid this hassle is to import only the wanted objects from the module. To do this, you use the from operator. You use it in the form of from modulename import itemname. Here is an example:
Code Example importing individual objects### IMPORT ITEMS DIRECTLY INTO YOUR PROGRAM # import them from modulename import itemname from modulename import itemname
Classes using in python
Creating a Class
What is a class? Think of a class as a blueprint. It isn't something in itself, it simply describes how to make something. You can create lots of objects from that blueprint - known technically as an instance.So how do you make these so-called 'classes'? very easily, with the class operator:
Code Example - defining a class
# Defining a class class class_name: [statement 1] [statement 2] [statement 3] [etc]
#!/usr/bin/env python
class Shape :
def __init__(self,x,y):
self.x = x
self.y = y
description = "this shape has not been descsrbed yet"
author = "Nobody claimed "
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
What you have created is a description of a shape (That is, the variables) and what operations you can do with the shape (That is, the fuctions). This is very important - you have not made an actual shape, simply the description of what a shape is. The shape has a width (x), a height (y), and an area and perimeter (area(self) and perimeter(self)). No code is run when you define a class - you are simply making functions and variables.
The function called __init__ is run when we create an instance of Shape - that is, when we create an actual shape, as opposed to the 'blueprint' we have here, __init__ is run. You will understand how this works later.
self is how we refer to things in the class from within itself. self is the first parameter in any function defined inside a class. Any function or variable created on the first level of indentation (that is, lines of code that start one TAB to the right of where we put class Shape is automatically put into self. To access these functions and variables elsewhere inside the class, their name must be preceeded with self and a full-stop (e.g. self.variable_name).
Using a class
Its all well and good that we can make a class, but how do we use one? Here is an example, of what we call creating an instance of a class. Assume that the code example 2 has already been run:rectangle = Shape(100,45)
The __init__ function really comes into play at this time. We create an instance of a class by first giving its name (in this case, Shape) and then, in brackets, the values to pass to the __init__ function. The init function runs (using the parameters you gave it in brackets) and then spits out an instance of that class, which in this case is assigned to the name rectangle.
Think of our class instance, rectangle, as a self-contained collection of variables and functions. In the same way that we used self to access functions and variables of the class instance from within itself, we use the name that we assigned to it now (rectangle) to access functions and variables of the class instance from outside of itself. Following on from the code we ran above, we would do this:
#finding the area of your rectangle:
print rectangle.area()
#finding the perimeter of your rectangle:
print rectangle.perimeter()
#describing the rectangle
rectangle.describe("A wide rectangle, more than twice as wide as it is tall")
#making the rectangle 50% smaller
rectangle.scaleSize(input("write the scale able value"))
#re-printing the new area of the rectangle
print rectangle.area()
As you see, where self would be used from within the class instance, its assigned name is used when outside the class. We do this to view and change the variables inside the class, and to access the functions that are there.
We aren't limited to a single instance of a class - we could have as many instances as we like. I could do this:
longrectangle = Shape(120,10) fatrectangle = Shape(130,120)
and both longrectangle and fatrectangle have their own functions and variables contained inside them - they are totally independent of each other. There is no limit to the number of instances I could create.
Monday, June 14, 2010
A Calculator Program in Python using functions and loops
Using a function
#calculator program
#this variable tells the loop whether it should loop or not.
# 1 means loop. anything else means don't loop.
loop = 1
#this variable holds the user's choice in the menu:
choice = 0
while loop == 1:
#print what options you have
print "Welcome to calculator.py"
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
choice = input("Choose your option: ")
if choice == 1:
add1 = input("Add this: ")
add2 = input("to this: ")
print add1, "+", add2, "=", add1 + add2
elif choice == 2:
sub2 = input("Subtract this: ")
sub1 = input("from this: ")
print sub1, "-", sub2, "=", sub1 - sub2
elif choice == 3:
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print mul1, "*", mul2, "=", mul1 * mul2
elif choice == 4:
div1 = input("Divide this: ")
div2 = input("by this: ")
print div1, "/", div2, "=", div1 / div2
elif choice == 5:
loop = 0
print "Thank you for using calculator.py!"
Define Your Own Functions
# calculator program # NO CODE IS REALLY RUN HERE, IT IS ONLY TELLING US WHAT WE WILL DO LATER # Here we will define our functions # this prints the main menu, and prompts for a choice def menu(): #print what options you have print "Welcome to calculator.py" print "your options are:" print " " print "1) Addition" print "2) Subtraction" print "3) Multiplication" print "4) Division" print "5) Quit calculator.py" print " " return input ("Choose your option: ") # this adds two numbers given def add(a,b): print a, "+", b, "=", a + b # this subtracts two numbers given def sub(a,b): print b, "-", a, "=", b - a # this multiplies two numbers given def mul(a,b): print a, "*", b, "=", a * b # this divides two numbers given def div(a,b): print a, "/", b, "=", a / b # NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN loop = 1 choice = 0 while loop == 1: choice = menu() if choice == 1: add(input("Add this: "),input("to this: ")) elif choice == 2: sub(input("Subtract this: "),input("from this: ")) elif choice == 3: mul(input("Multiply this: "),input("by this: ")) elif choice == 4: div(input("Divide this: "),input("by this: ")) elif choice == 5: loop = 0 print "Thankyou for using calculator.py!"
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
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.
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
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.
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'
)
python manage.py sql polls
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:- python manage.py validate -- Checks for any errors in the construction of your models.
- python manage.py sqlcustom polls -- Outputs any custom SQL statements (such as table modifications or constraints) that are defined for the application.
- python manage.py sqlclear polls -- Outputs the necessary DROP TABLE statements for this app, according to which tables already exist in your database (if any).
- python manage.py sqlindexes polls -- Outputs the CREATE INDEX statements for this app.
- python manage.py sqlall polls -- A combination of all the SQL from the sql, sqlcustom, and sqlindexes commands.
Now, run syncdb again to create those model tables in your database:
python manage.py syncdb
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
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>]
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()
Tuesday, June 8, 2010
Grub 2 after reinstalling Windows XP/Vista/Win7
Using Ubuntu 9.10 livecd or higher
Here assuming the Ubuntu partition is sda7,and /boot partition is sda6 (if you have a separate /boot partition).
Boot up ubuntu from the livecd,open terminal and run:
If you miss “grub.cfg” file,use following to recreate:
Using the cd/usb boot up with grub
open the Terminal
Boot up the grub menu.Type:
Here assuming the Ubuntu partition is sda7,and /boot partition is sda6 (if you have a separate /boot partition).
Boot up ubuntu from the livecd,open terminal and run:
sudo -i mount /dev/sda7 /mnt mount /dev/sda6 /mnt/boot #skip this one if not have a separate /boot partition grub-install --root-directory=/mnt/ /dev/sda
If you miss “grub.cfg” file,use following to recreate:
mount --bind /proc /mnt/proc mount --bind /dev /mnt/dev mount --bind /sys /mnt/sys chroot /mnt update-grub umount /mnt/sys umount /mnt/dev umount /mnt/proc exit
Using the cd/usb boot up with grub
open the Terminal
Boot up the grub menu.Type:
grub>find /boot/grub/core.img grub>root (hdx,y) (previous command will output the x,y) grub>kernel /boot/grub/core.img grub>boot
After the boot command,you’ll go into grub2 menu.Select to boot up ubuntu,and run this command to restore grub:
sudo grub-install /dev/sda
Saturday, June 5, 2010
Ubuntu - LAMP php5 userdir
So you migrated your primary webserver to Ubuntu LTS and suddenly your
users are complaining that their userdir php pages are not working. They
keep being asked to download their php pages or phtml, or whatever.
Their user blogs are not working. You have unhappy users, and by this
time you are probably one as well.
This may have come up in an earlier upgrade, but whether it is 9.10-10.04 or 8.04lts-10.04lts only is pretty irrelevant. You're feeling the pain.
You have two choices. Tell your users to move to a dedicated hosting environment of their own, or re-enable php scripting in the apache web server.
and change or comment the following lines to look like:
then restart apache.
This may have come up in an earlier upgrade, but whether it is 9.10-10.04 or 8.04lts-10.04lts only is pretty irrelevant. You're feeling the pain.
You have two choices. Tell your users to move to a dedicated hosting environment of their own, or re-enable php scripting in the apache web server.
Code:
sudo nano /etc/apache2/mods-available/php5.conf
Look for the lines that look like:
Code:
<IfModule mod_userdir.c> <Directory /home/*/public_html> php_admin_value engine Off </Directory> </IfModule>
Code:
# <IfModule mod_userdir.c> # <Directory /home/*/public_html> # php_admin_value engine Off # </Directory> # </IfModule>
Code:
sudo /etc/init.d/apache2 restart
And tell your users that they may need to restart their browsers. (or if
they can figure out how, clear their web cache.)
Friday, June 4, 2010
Install Server Packages (script)
sudo apt-get install apache2
sudo apt-get install openssh-server
sudo apt-get install php5 libapache2-mod-php5
sudo apt-get install mysql-server
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
sudo apt-get install phpmyadmin
sudo apt-get install php5-mysql mysql-client
sudo /etc/init.d/apache2 restart
##Activating the User's public_html Directory with userdirectory
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/userdir.conf userdir.conf
sudo ln -s ../mods-available/userdir.load userdir.load
sudo /etc/init.d/apache2 restart
apt-get install postgresql
sudo apt-get install phppgadmin
apt-get install vsftpd
apt-get install links
apt-get install vim
apt-get install joe
Install TCC(Testing And Consultancy Cell) Software Using Script
#/bin/bash
echo -n "Script ready enter Y to continue : "
read yes
if [ "$yes" = "y" ]
then
echo "Script Run"
else
echo "Exit"
exit
fi
cd /media/JAGDEEP
cp tcc.tar.gz ~/public_html
cd ~/public_html
chmod 777 tcc.tar.gz
tar zxvf tcc.tar.gz
chmod -R 755 ~/public_html
echo " Create Mysql database tc and prince_rou "
echo " Using command #create database tc ; create database prince_rou"
echo -n " Enter your Mysql Root Password : "
# Connect to the local database server as user root
# You will be prompted for a password.
mysql -h localhost -u root -p
#
# Now we see the 'mysql>' prompt and we can run
# the following to create a new database for Paul.
#
mysql> create database tcdb;
Query OK, 1 row affected (0.00 sec)
#
# Now we create the user paul and give him full
# permissions on the new database
mysql> grant CREATE,INSERT,DELETE,UPDATE,SELECT on pauldb.* to paul@localhost;
Query OK, 0 rows affected (0.00 sec)
#
# Next we set a password for this new user
#
mysql> set password for paul@localhost = password('mysecretpassword');
Query OK, 0 rows affected (0.00 sec)
#
# Cleanup and ext
mysql> flush privileges;
mysql> exit;
echo "Database created"
# Restore the databases
cd /media/JAGDEEP
mysql -u root -p tc < tc.sql
mysql -u root -p prince_rou < prince_rou.sql
echo " OK Report"
sudo apt-get install openssh-server
sudo apt-get install php5 libapache2-mod-php5
sudo apt-get install mysql-server
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
sudo apt-get install phpmyadmin
sudo apt-get install php5-mysql mysql-client
sudo /etc/init.d/apache2 restart
##Activating the User's public_html Directory with userdirectory
cd /etc/apache2/mods-enabled
sudo ln -s ../mods-available/userdir.conf userdir.conf
sudo ln -s ../mods-available/userdir.load userdir.load
sudo /etc/init.d/apache2 restart
apt-get install postgresql
sudo apt-get install phppgadmin
apt-get install vsftpd
apt-get install links
apt-get install vim
apt-get install joe
Install TCC(Testing And Consultancy Cell) Software Using Script
#/bin/bash
echo -n "Script ready enter Y to continue : "
read yes
if [ "$yes" = "y" ]
then
echo "Script Run"
else
echo "Exit"
exit
fi
cd /media/JAGDEEP
cp tcc.tar.gz ~/public_html
cd ~/public_html
chmod 777 tcc.tar.gz
tar zxvf tcc.tar.gz
chmod -R 755 ~/public_html
echo " Create Mysql database tc and prince_rou "
echo " Using command #create database tc ; create database prince_rou"
echo -n " Enter your Mysql Root Password : "
# Connect to the local database server as user root
# You will be prompted for a password.
mysql -h localhost -u root -p
#
# Now we see the 'mysql>' prompt and we can run
# the following to create a new database for Paul.
#
mysql> create database tcdb;
Query OK, 1 row affected (0.00 sec)
#
# Now we create the user paul and give him full
# permissions on the new database
mysql> grant CREATE,INSERT,DELETE,UPDATE,SELECT on pauldb.* to paul@localhost;
Query OK, 0 rows affected (0.00 sec)
#
# Next we set a password for this new user
#
mysql> set password for paul@localhost = password('mysecretpassword');
Query OK, 0 rows affected (0.00 sec)
#
# Cleanup and ext
mysql> flush privileges;
mysql> exit;
echo "Database created"
# Restore the databases
cd /media/JAGDEEP
mysql -u root -p tc < tc.sql
mysql -u root -p prince_rou < prince_rou.sql
echo " OK Report"
Thursday, June 3, 2010
Migrate a SQL Server or Access database to MySQL
Migration Tools
There are a wide variety of tools available to help you migrate a SQL Server or Access database to MySQL. We'll look at several different tools so you can choose the one that best suits your needs. The tools we will look at will include the following:- MSSQL2MYSQL
- Microsoft DTS
- SQLyog
- Access Export
- Text Import/Export
MSSQL2MYSQL
MSSQL2MYSQL is a creation of Michael Kofler, author of The Definitive Guide to MySQL by Apress. MSSQL2MYSQL is a Visual Basic script that can be executed using either a Microsoft Visual Basic 6 installation or an application that supports VBA such as Microsoft Word or Excel.Details on usage can be found at the author's web site, which also includes a listing of GUI front-ends that can be used to make MSSQL2MYSQL a bit more user-friendly for non-programmers.
To use MSSQL2MYSQL with VB6, simply copy the text located at http://www.kofler.cc/mysql/mssql2mysql.txt and paste it into the code section of a VB form. You will need to change the constants at the beginning of the code to match your SQL Server and MySQL installations, and you can then proceed to run the VB6 application and your conversion will take place. MSSQL2MYSQL does not provide any visual feedback on the progress of your conversion, and provides a simple messagebox upon completion.
A nice feature of MSSQL2MYSQL is the ability to dump all statements into a text file, which you can then review and edit before executing on the MySQL server.
Microsoft Data Transformation Services
Microsoft DTS is a data manipulation tool that is included with Microsoft SQL Server. DTS is excellent for moving data between various formats and systems such as databases, spreadsheets, and even HTML. The Microsoft Data Transformation Service can be very complex, but most of us will only ever need to use the Import/Export Wizard that is included with DTS.Using DTS is fairly straightforward, you choose an ODBC data source to read data from, and then select an ODBC data source to convert the data to. You are then given a list of tables to convert, with an option of renaming the destination table and even performing basic transformations on the data before it is inserted into the target database. These transformations are performed using Visual Basic scripting. In addition, you are given control over the table creation statements to be used, allowing you to fine-tune the MySQL table definitions to add parameters such as table handler (InnoDB, BDB, etc) to the script that will be executed.
DTS also has the ability to perform scheduled data transformations, something that can be very useful when you are using MySQL for analysis of SQL Server data or when you just want the latest data available as you work on your application migration.
SQLyog
SQLyog is a third-party commercial tool available to help administrators manage MySQL in a GUI environment. SQLyog is provided by by webyog, a MySQL partner, and a thirty day trial of the tool is provided. SQLyog provides an ODBC import tool that is similar to DTS, offering a straightforward interface that is perhaps even simpler to use than DTS.SQLyog is capable of scheduled imports of data, and can also be used to synchronize both data and schema between multiple MySQL servers.
Access Export
If you are a Microsoft Access user but do not have access to Microsoft DTS or SQLyog, you may want to use the export capability of Microsoft Access. Access can export its tables to a variety of formats, including ODBC. This allows you to export an Access table to MySQL by way of the Connector/ODBC ODBC driver provided by MySQL AB.To export an Access table to MySQL, right-click on the table in question and choose the 'Export' option. After several steps your data will be exported to MySQL. The column-type choices made by Access may need to be modified, and you should be aware that Access will not export index information with the data, meaning that you will need to implement indexes on your tables after exporting them.
Text Import/Export
One final way to import data is to export the data from MSSQL/Access in a text format and import it directly into MySQL. When exporting, common formats such as tab-delimited or comma-delimited will work fine for later import into MySQL.When taking this approach, you will need to manually create the MySQL tables, then import the data with the
LOAD DATA
command in
the mysql
command-line client. Additional information on the LOAD DATA
command can be
found in the "LOAD
DATA INFILE syntax" section of the MySQL Reference Manual.While perhaps the most labor-intensive and time-consuming, this approach gives you the highest level of control over table schema as you manually create the tables before importing data.
Tuesday, June 1, 2010
Quick install guide Django.
Install Python
Get Python at http://www.python.org
You can verify that Python’s installed by typing python from your shell; you should see something like :(on terminal)#Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
Remove any old versions of Django
If you are upgrading your installation of Django from a previous version, you will need to uninstall the old Django version before installing the new version.Install Django
You've got three easy options to install Django:- Install a version of Django provided by your operating system distribution. This is the quickest option for those who have operating systems that distribute Django.
- Install an official release. This is the best approach for users who want a stable version number and aren't concerned about running a slightly older version of Django.
Option 1. Get the latest official version
The latest official version is 1.2.1 Here's how to get it:First, download Django-1.2.1.tar.gz. Then:
tar xzvf Django-1.2.1.tar.gz
cd Django-1.2.1
sudo python setup.py install
- Install the latest development version. This is best for users who want the latest-and-greatest features and aren't afraid of running brand-new code.
Option 2. Get the latest development version
The latest and greatest Django version is the one that's in our Subversion repository (our revision-control system). Get it using this shell command, which requires Subversion:
svn co http://code.djangoproject.com/svn/django/trunk/
After you get it
See the installation guide for further instructions.
Install Apache and mod_wsgi
Basic Configuration
Once you’ve got mod_wsgi installed and activated, edit your httpd.conf file and add:WSGIScriptAlias / /path/to/mysite/apache/django.wsgi
Next we'll need to actually create this WSGI application, so create the file mentioned in the second part of WSGIScriptAlias and add:
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
sys.path.append('/usr/local/django')
Get your database running
If you plan to use Django’s manage.py syncdbSELECT, INSERT, UPDATE and DELETEALTER TABLE privileges during syncdb but won’t issue ALTER TABLE statements on a table once syncdb permissions. On some databases, Django will need command to automatically create database tables for your models, you’ll need to ensure that Django has permission to create and alter tables in the database you’re using; if you plan to manually create the tables, you can simply grant Django has created it.
Installing an official release
- Download the latest release from our download page.
- Untar the downloaded file (e.g. tar xzvf Django-NNN.tar.gz, where NNN is the version number of the latest release). If you're using Windows, you can download the command-line tool bsdtar to do this, or you can use a GUI-based tool such as 7-zip.
- Change into the directory created in step 2 (e.g. cd Django-NNN).
- If you're using Linux, Mac OS X or some other flavor of Unix, enter the command sudo python setup.py install at the shell prompt. If you're using Windows, start up a command shell with administrator privileges and run the command setup.py install.
For more detial click here
Creating a project
If this is your first time using Django, you’ll have to take care of someinitial setup. Namely, you’ll need to auto-generate some code that establishes aDjango project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings. From the command line, cd into a directory where you’d like to store your code, then run the command django-admin.py startproject mysite. This wil lcreate a mysite directory in your current directory.
The development server Let's verify this worked. Change into the mysite directory, if you haven't already, and run the command python manage.py runserver. You'll see the following output on the command line: Validating models...
0 errors found. Django version 1.0, using settings 'mysite.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.Database setup
Now, edit settings.py. It's a normal Python module with module-level variables representing Django
settings. Change the following keys in the DATABASES 'default' item to match your databases
connection settings.
ENGINE -- Either
If you're new to databases, we recommend simply using SQLite (by setting ENGINE to
'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql' or 'django.db.backends.sqlite3'. Other backends are also available. NAME -- The name of your database. If you're using SQLite, the database will be a file on your
computer; in that case, NAME should be the full absolute path, including filename, of that file.
If the file doesn't exist, it will automatically be created when you synchronize the database for the
first time (see below).When specifying the path, always use forward slashes, even on
Windows (e.g. C:/homes/user/mysite/sqlite3.db). USER -- Your database username (not used for SQLite). PASSWORD-- Your database password (not used for SQLite). HOST --The host your database is on. Leave this asan empty string if your database server is on the
same physical machine (not used for SQLite).
'django.db.backends.sqlite3'). SQLite is included as part of Python 2.5 and later, so you won't
need to install anything else.
While you're editing settings.py, take note of the
INSTALLED_APPS setting towards the bottom of the file. That variable holds the names of all Django applications that are
activated in this Django instance. Apps can be used in multiple projects, and you can package and
distribute them for use by others in their projects.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
These applications are included by default as a convenience for the common case.
- django.contrib.auth -- An authentication system.
- django.contrib.contenttypes -- A framework for content types.
- django.contrib.sessions -- A session framework.
- django.contrib.sites -- A framework for managing multiple sites with one Django installation.
Each of these applications makes use of at least one database table, though,so we need to create the
tables in the database before we can use them. To do that, run the following command:
python manage.py syncdb
Subscribe to:
Posts (Atom)