Search Google

Friday, 25 September 2015

Share market knowledge

Hello guys .. I had found this artical very useful . This article is in hindi . Just read and understand it . It reveals the Dark side of Market.

A must for nerd trader:


----------------------------------------------------------------------------------------------------------------------------------------------------
Sab ke Sab Chor hai.........


Quote:
Is Bazar me sab chor baithe huye hai ... ab yeh aap par nirbhar karta hai ki aap kitna bach paate hai... mai bhee share baazaar me nivesh/trade karta hoon... in sab choro se bachne kaa sabse achha tareeka yah hai ki aap unse apane trade sambandhit saari jaankari le bhale hi iski jaroorat aapko ho yaa naa ho... aur yadi ve koi jankari dene me aaana- kaani kare to in logoko RTI ki dhamaki de ... itne me to yah log raste par aa jaate hai...
shuruvaat me account kholne ke baad inka vyavhaar badal jaataa hai, aap sab ne mahsoos kiyaa hoga to aap apna bhee vyvhaar badal de, hamesha in se jara Rude hokar baate kare....
lekin account kholane ke pahle aap kuchh baate sunishchit kar le....
1. kabhi bhi DIAL & TRADE jaisi koi suvidhaa ke chakkar me naa pade ( agar aap TRADER ho to )

2. kam Brokerage hamesha suvidhaajanak nahee hoti...

3. in logo se T+1,2,3,4,5 , MARGIN aur M2M ke matlab pooch aur samajh le...

4. kabhi bhi jara si bhi dikkat ho to inke Branch/Area/ Regional/Zonal Head ke pass jaakar use Hadkane me jara bhee deri nahi kare( jab yeh log aapse beimaani karne me nahi darte hai to aap apane paise ke liye ladne me bhi naa dare " fir is baat ka koi farak nahee padhta hai ki yeh HARD EARNED MONEY yaa EASY EARNED MONEY " aakhirkaar yah aapki hi hai.....

5. yadi aap Online Trading kare to DIET ODIN jaisa hi koi software le... aapake broadband par yah VSAT ki tulna me keval 1/3 seconds ki deri se hi utaar- chadaav ( fluctuation) dikhataa hai ... jabaki koi doosri Browser Based application 2-3 seconds se lekar 5 minutes tak ki deri karti hai .... bhale hi woh ICICI Direct , Relaince Money ka INSTATRADE, Kotat kaa KEAT ho yaa fir Angel walo ka ANGEL TRADE ....

Vaise yah jo DIETODIN software hai yah wahi soft ware hai jo aap kisi bhi Broker ki Screen par Lal Neele utar chadavo ke sath dekhte hai... meri jaankaare ke anusaar abhi keval Angel Broking waale hi yah software de rahe hai par isake liye 2-3 hajaar / mahine ki kam se kam brokerage ki maang karte hai ...

6. kabhee bhee in logo ke BTST calls par dhyan naa de... yah sirf Brokerage Banane ki chaal hoti hai ....

7. FINALLY & MOST IMPORTANTLY , BUSINESS NEWS channel sabase bade chor hai, in Business News Channels par recommend kiye gaye Stocks par kabhi bhi apna paisa naa lagaye .... yah �aksar� keval unhi counters ki baate karte hai jo ki chal chuke hote hai... inki baat sunkar aap keval oopari staro par apna paisa fansa sakte hai aur kuchh nahi kar sakte hai...

PAISA KAMANE KAA SABASE SAHI TARIKA :-
Jab bhi koi Counter jaise Relaince , L& T , BHEL, ONGC, GAIL ,RCOM yaa aapaki pasand kaa koi bhi Counter jaise ki meri pasand NTPC , DLF, SAIL aur TTML hai ..... 3 se 10 % tak Correct ho jaave to us par apne paas uplabdh kul 40% pasia hi lagaye, aur yadi aapaka share 10% aur neeche aata hai to 35 % paisa aur lagaye... aur intzaar kare ... aap kabhi bhi ghata nahi kaatenge...

PAISA NAA GAVANE KAA SABASE SAHI TARIKA :-
aap yadi F& O me Trade karna chahate hai to kabhi bhi haa kabhi bhi kisi bhi Position ko carry naa kare bhale hi woh ASHOK LEYLAND hi kyu naa ho ( Jiska Span Margin 55 000 se 65000 hi hai) JAB TAK KI AAPKE ACCOUNT ME 5 LAKH Rs naa ho ... baat badi ajeeb lagati hai lekin mera Ganit to yahi kahta hai... aur Cash Market me bhi Nivesh aur Trade karte samay ho sake to KAM se KAM 1 lakh Rs. se Nivesh /Trade kare...
kyuki har jagah ki tarah yaha bhi SAARI BADI MACHHLIYA CHOTI MACHHLIYO PAR HI PALTI HAI....

PS: ho sake to kisi Retail Niveshak/ traders ke samooh ke sadasya ban jaaye jisase aapka partyaksh sampark ho... aur har 3-4 din me SEBI ki website par jaate rahe ( bhale hi yah kitni hi dheemi khule)

Monday, 14 September 2015

Multidimensional Arrays

Multidimensional Arrays

 http://php.net/manual/en/control-structures.foreach.php

 http://www.informit.com/articles/article.aspx?p=31840&seqNum=4

 

Laymens terms:

A recursive function is a function that calls itself

A bit more in depth:

If the function keeps calling itself, how does it know when to stop? You set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.
What was a good learning example for me, since I have a strong background in math, was factorial. By the comments below, it seems the factorial function may be a bit too much, I'll leave it here just in case you wanted it.

function fact($n)

  { if ($n === 0)  

{ // our base case return 1; } 

 else { return $n * fact($n-1); // <--calling itself. } }

In regards to using recursive functions in web development, I do not personally resort to using recursive calls. Not that I would consider it bad practice to rely on recursion, but they shouldn't be your first option. They can be deadly if not used properly.

 

Arrays do not have to be a simple list of keys and values—each location in the array can hold another array. This way, we can create a two-dimensional array. You can think of a two dimensional array as a matrix, or grid, with width and height or rows and columns.
If we want to store more than one piece of data about each of Bob's products, we could use a two-dimensional array.
Figure 3.3 shows Bob's products represented as a two-dimensional array with each row representing an individual product and each column representing a stored product attribute.
Figure 3.3Figure 3.3 We can store more information about Bob's products in a two- dimensional array.
Using PHP, we would write the following code to set up the data in the array shown in Figure 3.3.
$products = array( array( 'TIR', 'Tires', 100 ),
          array( 'OIL', 'Oil', 10 ),
          array( 'SPK', 'Spark Plugs', 4 ) );
You can see from this definition that our products array now contains three arrays.
To access the data in a one-dimensional array, recall that we need the name of the array and the index of the element. A two-dimensional array is similar, except that each element has two indices—a row and a column. (The top row is row 0 and the far left column is column 0.)
To display the contents of this array, we could manually access each element in order like this:
echo '|'.$products[0][0].'|'.$products[0][1].'|'.$products[0][2].'|<br />';
echo '|'.$products[1][0].'|'.$products[1][1].'|'.$products[1][2].'|<br />';
echo '|'.$products[2][0].'|'.$products[2][1].'|'.$products[2][2].'|<br />';
Alternatively, we could place a for loop inside another for loop to achieve the same result.
for ( $row = 0; $row < 3; $row++ )
{
 for ( $column = 0; $column < 3; $column++ )
 {
  echo '|'.$products[$row][$column];
 }
 echo '|<br />';
}
Both versions of this code produce the same output in the browser:
|TIR|Tires      |100|
|OIL|Oil        |10 |
|SPK|Spark Plugs|4  |
The only difference between the two examples is that your code will be shorter if you use the second version with a large array.
You might prefer to create column names instead of numbers as shown in Figure 3.3. To do this, you can use associative arrays. To store the same set of products, with the columns named as they are in Figure 3.3, you would use the following code:
$products = array( array( Code => 'TIR', 
             Description => 'Tires', 
             Price => 100 
            ),
          array( Code => 'OIL', 
             Description => 'Oil', 
             Price => 10 
            ),
          array( Code => 'SPK', 
             Description => 'Spark Plugs', 
             Price =>4 
            ) 
         );
This array is easier to work with if you want to retrieve a single value. It is easier to remember that the description is stored in the Description column than to remember that it is stored in column 1. Using associative arrays, you do not need to remember that an item is stored at [x][y]. You can easily find your data by referring to a location with meaningful row and column names.
We do however lose the ability to use a simple for loop to step through each column in turn. Here is one way to write code to display this array:
for ( $row = 0; $row < 3; $row++ )
{
 echo '|'.$products[$row]['Code'].'|'.$products[$row]['Description'].
    '|'.$products[$row]['Price'].'|<br />';
}
Using a for loop, we can step through the outer, numerically indexed $products array. Each row in our $products array is an associative array. Using the each() and list() functions in a while loop, we can step through the associative arrays. Therefore, we need a while loop inside a for loop.
for ( $row = 0; $row < 3; $row++ )
{
 while ( list( $key, $value ) = each( $products[ $row ] ) )
 {
  echo "|$value";
 }
 echo '|<br />';
}
We do not need to stop at two dimensions—in the same way that array elements can hold new arrays, those new arrays in turn can hold more arrays.
A three-dimensional array has height, width, and depth. If you are comfortable thinking of a two-dimensional array as a table with rows and columns, imagine a pile or deck of those tables. Each element will be referenced by its layer, row, and column.
If Bob divided his products into categories, we could use a three-dimensional array to store them. Figure 3.4 shows Bob's products in a three-dimensional array.
Figure 3.4Figure 3.4 This three-dimensional array allows us to divide products into categories.
From the code that defines this array, you can see that a three-dimensional array is an array containing arrays of arrays.
$categories = array( array ( array( 'CAR_TIR', 'Tires', 100 ),
               array( 'CAR_OIL', 'Oil', 10 ),
               array( 'CAR_SPK', 'Spark Plugs', 4 )
              ),
           array ( array( 'VAN_TIR', 'Tires', 120 ),
               array( 'VAN_OIL', 'Oil', 12 ),
               array( 'VAN_SPK', 'Spark Plugs', 5 )
              ),
           array ( array( 'TRK_TIR', 'Tires', 150 ),
               array( 'TRK_OIL', 'Oil', 15 ),
               array( 'TRK_SPK', 'Spark Plugs', 6 )
              )
          );
Because this array has only numeric indices, we can use nested for loops to display its contents.
for ( $layer = 0; $layer < 3; $layer++ )
{
 echo "Layer $layer<br />";
 for ( $row = 0; $row < 3; $row++ )
 {
  for ( $column = 0; $column < 3; $column++ )
  {
   echo '|'.$categories[$layer][$row][$column];
  }
  echo '|<br />';
 }
}
Because of the way multidim


Friday, 4 September 2015

PHP LOGIC PROGRAMMING





multidimensional 

<?php 
//Initialize the array using the array() function.
$flower_shop = array( 
"rose" => array( "5.00", "7 items", "red" ), 
"daisy" => array( "4.00", "3 items", "blue" ), 
"orchid" => array( "2.00", "1 item", "white" ), 
); 

//print "rose costs 5.00, and you get 7 items." 
echo "rose costs ".$flower_shop['rose'][0].", and you get ".$flower_shop['rose'][1]."."; 
//print "daisy costs 4.00, and you get 3 items." 
echo "daisy costs ".$flower_shop['daisy'][0].", and you get ".$flower_shop['daisy'][1]."."
//print "orchild costs 2.00, and you get 1 item. 
echo "orchid costs ".$flower_shop['orchid'][0].", and you get ".$flower_shop['orchild'][1]."."; 
?>

Friday, 7 August 2015

Advance PHP TUTORIAL MULTI–DIMENSIONAL ARRAYS

http://javascript.info/tutorial/browser-window-properties-and-methods

 

Example JS http://www.tutorialspoint.com/javascript/javascript_objects.htm

Try the following example.
<html>
   <head>
   <title>User-defined objects</title>
   
      <script type="text/javascript">
         // Define a function which will work as a method
         function addPrice(amount){
            with(this){
               price = amount;
            }
         }
         
         function book(title, author){
            this.title = title;
            this.author  = author;
            this.price = 0;
            this.addPrice = addPrice; // Assign that method as property.
         }
      </script>
      
   </head>
   <body>
   
      <script type="text/javascript">
         var myBook = new book("Perl", "Mohtashim");
         myBook.addPrice(100);
         
         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
      
   </body>
</html>
Output
Book title is : Perl 
Book author is : Mohtashim 
Book price is : 100

 

http://www.plus2net.com/html_tutorial/button-linking.php

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
   $num += 5;
}

function addSix(&$num)
{
   $num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result:
Original Value is 10
Original Value is 16 

When do we pass arguments by reference or pointer?

In C++, variables are passed by reference due to following reasons:
1) To modify local variables of the caller function: A reference (or pointer) allows called function to modify a local variable of the caller function. For example, consider the following example program where fun() is able to modify local variable of main().
void fun(int &x) {
    x = 20;
}
int main() {
    int x = 10;
    fun(x);
    cout<<"New value of x is "<<x;
    return 0;
}
Output:
New value of x is 20

PHP Functions retruning value

A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>

<?php
function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
This will display following result:
Returned value from the function : 30








 http://www.trans4mind.com/search
......................................................................................................
In javascript, you can use either single (') or double (") quotes and they behave the same. In php, it is different. Double quotes and single quotes aren't exactly the same.
$something="Oh something";

echo "My answer is $something.<br>";

//result is: My answer is Oh something
In the above, using double quotes, the variable $something is evaluated within the quotes and the result isn't what is expected: the variable is evaluated to Oh something. Variables, but not functions or constants, are evaluated even when enclosed in double quotes.
echo 'My answer is $something.<br>';

//result is: My answer is $something.
When single quotes are used, as above, the variable isn't evaluated and is printed on the screen literally as $something.

Escaping with the backslash \

The backslash character (\) can be used to escape quotes and variables. The next example repeats the idea that things are evaluated within double quotes:
$something="Oh something!";

echo "My answer is $something";

//result: My answer is Oh something!

So nothing new here, just a reminder. Next we use the backslash to escape the variable $something and also the double quotes around "is":

echo "<br>";
echo "My answer \"is\" \$something";

//result: My answer "is" $something
 ======================================
mysql_fetch_row ::Return row as aan enumrated array and each line contain a unique ID .example.
$result=mysql_query($query);
while($row=mysql_fetch_row($result))
{
print "$row[0]";
print "$row[1]";
print "$row[2]";
}

mysql_fetch_array ::Return row as anassociative or an enumrated array or both which is default .you can refer to outputs as databases fieldname rather then number .example.
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
print "$row['name']";
print "$row['address']";
print "$row['city']";
}

mysql_fetch_object  :: it return as an object on the place of array.

$result=mysql_query($query);
while($row=mysql_fetch_object($result))
{
print "$row->name";
print "$row->address";
print "$row->city";









 .............................................................................................................................................
form.php
PHP Code:
<input type="file" name="image[]">
<
input type="file" name="image[]">  
// array image[] is called as $_FILES['image']
output.php
PHP Code:
// array image[] is called as $_FILES['image']
if(!empty($_FILES['image']['name'])){
    foreach(
$_FILES['image']['name'] as $k => $v){
        print 
'$_FILES["image"]["name"]["'.$k.'"] = '.$v;
    }
}  


o/p



PHP Code:
Array
(
    [
image] => Array
        (
            [
name] => Array
                (
                    [
0] => 
                    [
1] => 
                )

            [
type] => Array
                (
                    [
0] => 
                    [
1] => 
                )

            [
tmp_name] => Array
                (
                    [
0] => 
                    [
1] => 
                )

            [
error] => Array
                (
                    [
0] => 4
                    
[1] => 4
                
)

            [
size] => Array
                (
                    [
0] => 0
                    
[1] => 0
                
)

        )



=======================================================

Multiple File Upload with PHP and MySQL


<?php
if(isset($_FILES['files'])){
    $errors= array();
 foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
  $file_name = $key.$_FILES['files']['name'][$key];
  $file_size =$_FILES['files']['size'][$key];
  $file_tmp =$_FILES['files']['tmp_name'][$key];
  $file_type=$_FILES['files']['type'][$key]; 
        if($file_size > 2097152){
   $errors[]='File size must be less than 2 MB';
        }  
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="user_data";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);  // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"user_data/".$file_name);
            }else{         //rename the file if another one exist
                $new_dir="user_data/".$file_name.time();
                 rename($file_tmp,$new_dir) ;    
            }
            mysql_query($query);   
        }else{
                print_r($errors);
        }
    }
 if(empty($error)){
  echo "Success";
 }
}
?>


<form action="" method="POST" enctype="multipart/form-data">
 <input type="file" name="files[]" multiple="" />
 <input type="submit"/>
</form>

















------------------------------------------------------------------------------------------

http://forum.codecall.net/forum/158-php-tutorials/ BEST PHP TUTS

https://www.google.co.in/search?q=php+logical+problems 

MULTI–DIMENSIONAL ARRAYS

Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material.
A 2 dimensional array consists of rows and columns.

Figure 082:   Two-dimensional Array
Although we think of a 2 dimensional array as consisting of rows and columns, it is actually linearly stored by row.   This is an important piece of information that will come into play when passing arrays as parameters in functions.

Figure 083:   Two-dimensional Array Storage
3 dimensional array

Figure 084:   Three-dimensional Array
There are no review questions for this reading assignment.
$this

with $this you can call functions and variables of a class. It means this class or this document. In some programming language we call it me. Take a look at this code
class Example {
public $name = "papabear";
public $color;

function Sample() {
echo "This is an example";
}

function SayName() {
echo $this->name;
}

function saySample() {
$this->Sample();
}
}

$obj = new Example();
$obj->SayName();
echo "<br/>";
$obj->saySample();


output :

Quote
papabear
This is an example


to be more clear.. $this applies to a class that we are IN. here's another example

class Example {
   public $name = "papabear";
   public $color;

  function Sample() {
     echo "This is an example";
  }

  function SayName() {

     $name = "alleo";
     echo $this->name;

  }

  function saySample() {
    $this->Sample();
  }
}

$obj = new Example();
$obj->SayName();

Output :

papabear


Take a look at the


function SayName() {

$name = "alleo";
echo $this->name;

}

have you noticed the difference? You can't use a class property or variable if you didn't call them using $this

$name and $this->name is different from each other.. $name is a variable or a property or the function while the $this->name is a global variable/property, please don't be confused with that. I know it's confusing but please.. bare with me :)


That's all for today's tutorial.. Thanks for your time, if you have some questions and found some error in my tutorial please feel free to reply.. I'm still learning this things and wants to share what I've learned.. I'm posting tutorials to learn from critics also :) see ya soon

More Powers
Papabear

-------------------------------------------------------------------------





CodeIgniter

 

http://www.formget.com/product/seo-php-script/ 

http://www.formget.com/codeigniter-paypal-checkout/ 


Saturday, 18 July 2015

life lesson how to be smart

बbई से सस्ते वियतनाम का हनाेई, पोलैंड का वारसा, मिस्र का शर्म अल शेख आैर थाईलैंड का बैंकाक शहर है।


महाभारत युद्ध के बाद जब पांडव जीत गए, युधिष्ठिर राजा बन गए, तब वो कुरुक्षेत्र में तीरों की शैय्या पर लेटे भीष्म पितामह से राजनीति की शिक्षा लेने पहुंचे। भीष्म ने युधिष्ठिर को जितनी भी बातें बताईं वे आज भी हमारे जीवन के लिए बहुत उपयोगी है। इंसान को किस तरह के लोगों से रिश्ते बनाने चाहिए और किस तरह के लोगों से हमेशा दूर रहना चाहिए, इसे लेकर भी भीष्म ने युधिष्ठिर को पूरा ज्ञान दिया।
आइए, जानते हैं कि भीष्म ने युधिष्ठिर को किन लोगों से हमेशा दूर रहने और दोस्ती ना करने का उपदेश दिया था -
1. आलसी - आलस मनुष्य का सबसे बड़ा शत्रु होता है। आलसी व्यक्ति जीवन में किसी भी अवसर का लाभ नहीं लेता। आलस की वजह से मनुष्य अपनी जिम्मेदारियां पूरी नहीं करता और सबकी नजरों में बुराई का पात्र बनता जाता है। ना तो वह अपने स्वास्थ्य के प्रति जागरुक रहता है, ना आपने कामों के प्रति। उसकी संगति से हम भी आलसी होने लगते हैं। इन्हीं कारणों से आलसी मनुष्य से कभी दोस्ती नहीं करनी चाहिए।

3. क्रोध करने वाला
बेवजह या अत्यधिक क्रोध करने वाले का व्यवहार दानव के समान माना जाता है। क्रोध करने से मनुष्य हमेशा ही अपना नुकसान करता है। कई बार निन्दा और हास्य का पात्र भी बन जाता है। ऐसे व्यक्ति से दोस्ती करके पर ना केवल खुद को बल्कि अपने परिजनों को भी हानि पहुंचती है। इसलिए क्रोध करने वालों से कभी मित्रता नहीं करनी चाहिए।
4. जलन या द्वेष रखने वाला
जो मनुष्य दूसरों के प्रति अपने मन में जलन या द्वेष की भावना रखता है, वह निश्चित ही छल-कपट करने वाला, पापी, धोखा देने वाला होता है। वह दूसरों के नीचा दिखाने के लिए किसी भी हद तक जा सकता है। जलन और द्वेष भावना रखने वाले के लिए सही-गलत के कोई पैमाने नहीं होते हैं। ऐसे व्यक्ति की दोस्ती हमें भी उसी की तरह दुराचारी बना देती है।

5. शराब पीने वाला
सामाजिक जीवन में सभी के लिए कुछ सीमाएं होती है। हर व्यक्ति को उन सीमाओं का हमेशा पालन करना चाहिए, लेकिन शराब पीने वाले मनुष्य के लिए कोई सीमा नहीं होती। शराब पीने के बाद उसे अच्छे-बुरे किसी का भी होश नहीं रहता है। ऐसा व्यक्ति अपने परिवार और मित्रों को कष्ट पहुंचाने वाला होता है। वह किसी भी समय आपके लिए परेशानी का कारण बन सकता है।

Tuesday, 9 June 2015

django tutorial for beginners create your first app

 

django-admin.py startproject myproject
creates a project and files like
  • __init__.py use files as an global modules
  • manage.py to manage project like, Syncdb, migrate, startserver
  • settings.py Contains The Project Settings
  • urls.py Contains Project URL,you can include the app url file
python manage.py startapp appname
creates a app inside my project and files like
  • __init__.py use files as an global modules
  • models.py You can write your model classes here
  • tests.py To write test cases
  • views.py App URLs

1 django-admin.py startproject myproject
creates a project and files like init.py, manage.py, settings.py, urls.py
2 python manage.py startapp appname
creates a app inside my project and files like init.py, models.py, tests.py, views.py
-------------------------------------------------------------------

Getting Django setup on Windows

A friend asked me how to setup an Django enviroment on Windows without the Cygwin fuzz. Here is the shortest steps I can think of:

1. Install Python3.4 as default path. (It should be "C:\Python34").
2. Open cmd.exe program on Windows and run the following commands:

    set PATH=%PATH%;C:\Python34;C:\Python34\Scripts
    pip install django
    python C:\Python34\Lib\site-packages\django\bin\django-admin.py startproject mysite
    cd mysite
    python manage.py syncdb

    (Follow prompts to setup an initial db. remember the user you used here.)

    python manage.py runserver

3. You are ready to django! Open your browser http://127.0.0.1:8000 to verify.
    Or login into http://127.0.0.1:8000/admin with the user you setup above.
  
What's next?
    Explore django with a guided tutorial here:
    https://docs.djangoproject.com/en/1.6/intro/tutorial01

  ----------------------------------------------------------------------------------




Django Basics - Installing Django and Setting Up a Project and App


This brief tutorial shows the basics of installing and setting up a simple app in Django that is used to submit and retrieve information about books you've read:
  • Part 1 - Installing and Setting up Django
  • Part 2 - Creating the Database Model
  • Part 3 - Django API vs Admin site
  • Part 4 - Django Templates and Views
Each part includes an accompanying video. You can download the source via Github - which includes all four parts. I will be delivering this tutorial from a Windows-perspective, but the Mac OS X perspective is pretty much the same.
This tutorial follows the first few sections of the official Django tutorial.
Videos - Part 1, Part 2, Part 3, Part 4
GitHub - https://github.com/mjhea0/django-tutorial
Django?
Developed in 1995 Django is one of, if not the most, popular Python web frameworks. It promotes rapid development via the model-view-controller architecture. You can learn more about it here.
Prerequisites:
  • You have Python 2.7 installed.
  • You have PIP installed. To install, you need to first install setup tools. Click here for a brief tutorial on how to do that. Then you can just run the command easy_install pip from the command prompt to install PIP.

Alright let's get started …

Part 1 - Installing Django

Open the command prompt with admin privileges and run the command-




pip install Django
-to install Django into your site-packages directory.

To setup, you need to create a new project. Within command prompt, navigate to the directory you wish to create the new project, then run the command -




python C:\Python27\Lib\site-packages\django\bin\django-admin.py startproject testproject
Your path to *django-admin.py* may be different, so make sure to tailor it if necessary. Also, *testproject* is the name of the created project. Feel free to name this whatever you like. ### Next you need to make sure everything was setup correctly. To do that, you can launch the Django server. First, navigate to your newly created directory (*testproject*, in my case), and then run the command-
python manage.py runserver
Open up a new browser window and navigate to http://localhost:8000/. If setup correctly, you will see the Welcome to Django screen. ### Let’s setup the database. Open up *settings.py* in the *testproject* directory with a text editor. (I use Notepad++.) Append *sqlite3* to the end of the Engine key and then add the path to the name key. You can name the database whatever you’d like because if the database doesn’t exist, Django will create it for you in the next step. The results should look like something similar to this (depending upon your path)-
'ENGINE': 'django.db.backends.sqlite3',    
'NAME': 'C:/Python27/django/testproject/test.db',
(Yes, use forward slashes.)

Finally, you need to create and then sync the database by navigating to the directory where manage.py is located (should be the project's main directory) and then running the following command-




python manage.py syncdb
Create a superuser. I used admin for both my username and password.
Alright, the setup is complete. You're now ready to start creating an app.

Part 2 - Creating the Database Model

Start by creating an app. Within command prompt, navigate to the testproject directory and then type the command-




python manage.py startapp books
CD into the directory. You should see a models.py file. This file is used to setup the entities and attributes for your database.

Go ahead and open models.py in Notepad++ and add in the following code:




class Books(models.Model):
  title = models.CharField(max_length=150)
  author = models.CharField(max_length=100)
  read = models.CharField(max_length=3)
This code should be relatively clear. This class defines the database fields- title, author, and read. The data in the read field will either be "yes" or "no" depending on whether you've read the book or not.
Since there is only one table, we don't need to establish a foreign key. The primary key, a unique id, will be automatically generated for us by Django's magic.
Save the file.

Now open up the settings.py file, scroll down to Installed Apps and add the app name, books, to the installed apps so that Django knows to include it. Your installed apps section should look like this-




INSTALLED_APPS = (
  'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
  'books',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)
Save the file.

CD back to the main project directory and run the command-




python manage.py sql books
-to display the actual SQL statements for creating the table. Did you notice the primary key?
Your output should look like this-



BEGIN;
CREATE TABLE "books_books" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(150) NOT NULL,
    "author" varchar(100) NOT NULL,
    "read" varchar(3) NOT NULL
)
;
COMMIT;
You can also use the following command to check to see if there are any errors in your models-



python manage.py validate

Finally, you need to run the following command to execute the SQL statements:




python manage.py syncdb
Next, I'll show you how to access the Django API to add data to the database.

Part 3 - Django API vs Admin site

First open up command prompt, navigate to your project directory, and then run the command-




python manage.py shell
This opens an interactive environment for us to use.

Next go ahead and import your app with the following command-




from books.models import Books

There's a number of different things you can do within this environment, but let's stick with adding data to our database. To add a row, run this command-




b = Books(title="To Kill a Mockingbird", author="Harper Lee", read="yes")
b.save()
b = Books(title="Brave New World", author="Aldous Huxley", read="yes")
b.save()
b = Books(title="War and Peace", author="Leo Tolstoy", read="no")
b.save()
Go ahead and add as many books as you'd like for practice.
Once complete, you can view the data in your database in a number of ways. I like to just use SQLite, which can be downloaded here. So, go ahead and open the text.db file which is located within your project's main directory, switch to the Browse Data tab, and then under the Table dropdown choose books_books. You should see all the books you added.
You can exit the Django interactive environment using the exit() command.
Okay, let's look at an even easier means of adding data using Django's admin site.

Open the settings.py file, scroll down to Installed Apps and uncomment the line 'django.contrib.admin',. Then save the file.

Update the database by running the command-




python manage.py syncdb

Next open the urls.py file within the books directory. You need to uncomment these three lines-




from django.contrib import admin
admin.autodiscover()
url(r'^admin/', include(admin.site.urls)),
Save the file and exit.

Now create a new file in your books directory called admin.py and add the following code to the file-




from books.models import Books
from django.contrib import admin
admin.site.register(Books)

Next, open up your models.py file and add these two lines of code-




def __unicode__(self):
  return self.title + " / " + self.author + " / " + self.read
Essentially, self refers to the current object.

Now start the development server - python manage.py runserver, point your browser to http://localhost:8000/admin, and enter your login credentials. You should see the Books app. And if you click the app, you should now see the data we added earlier.

Go ahead and add a few more books in. Try deleting a row as well. See how much easier that is in the Admin console?
So we're done with the Admin console. Hit CTRL+BREAK to exit. I'm also done showing you how to create and modify your app's model(s). Next, we'll look at how to modify what the user sees (views and templates).

Part 4 - Django Templates and Views

Again, in this final tutorial I'll go over how to create the public interface.

The first thing we need to do is setup the URL structure. Open up urls.py and then add this code to the urlpatterns-




url(r'^books/$', 'books.views.index'),
This is essentially a tuple that points a user to a Django page based on the URL that user visits. In this case the regular expression dictates that when the user visits any page with the ending /books they will be see the books.views.index page. This is a bit complicated, so be sure to visit the Django tutorial for more into.

Now to ensure that this is setup correctly run the server and then point your browser to http://localhost:8000/books.

As long as you get the error, ViewDoesNotExist at /books, then the url is setup correctly.
We need to actually write the view now.

Stop the server (CRTL+BREAK) and then within the books directory open views.py in Notepad++ and write the following code to test out your views-




from django.http import HttpResponse
def index(request):
  return HttpResponse("Hello. This is a test.")
Save the file. Run the server. And refresh the page. You should no longer see an error. Instead, you should just see a page with the words Hello. This is a test. in the top corner.

Okay, now let's display something a bit more meaningful - like a listing of all the books in the database. To do that, you need your views.py file to look like this-




from django.http import HttpResponse
from books.models import Books
def index(request):
    books_list = Books.objects.all()
    return HttpResponse(books_list)
-and then just hit refresh on your browser. (Remember: we didn't stop the server).
You should see all of the books in one long line. It looks bad, but it works.
Next, we're going to work with templates, which will allow us to easily create a much more readable output.

Start by making a new directory in the django directory, outside of the project, called templates. Within that directory, make a directory called books.

Next open up settings.py, scroll down to TEMPLATE_DIRS and add the template directory-




"C:/Python27/django/templates"
Yes, those are forward slashes. ### Now create a new file in your *temples\books* directory. Save it as index.html and add the following code-
<h1>My Fab Book Collection</h1>
{% if books_list %}
<ul>
{% for b in books_list %}
    <li>{{b.title}} | {{b.author}} | {{b.read}}</li>
{% endfor %}
</ul>
{% endif %}

Open views.py again and make it looks like this-




from django.http import HttpResponse
from books.models import Books
from django.template import Context, loader      
def index(request):
  books_list = Books.objects.all()
  t = loader.get_template('books/index.html')
  c = Context({'books_list': books_list,})
  return HttpResponse(t.render(c))
Basically, the loader is the path to the template we created, which then gets assigned to the Python object via the Context dictionary.

Save the file. Run the server. Refresh the http://localhost:8000/books page. There's the books. Looks a little better, too.

I know I said that I'd show to make it so a non-administrator can add data to the database - but I just realized that this would be another lesson in itself. So, I'm going to stop here. Feel free to view the Django Tutorial to learn how to add that functionality to your application.
In fact, the whole point to these tutorials is for you to get started with the Django tutorial. I bounced around a bit but I hope that you can now go through the tutorial a bit easier now that you have a starting off point.
Thanks for watching. See you next time.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 from http://www.programmersbook.com/page/21/Django-Beginner-Tutorial-Part-I/

  work with database command 

syncdb create the required tables as follows: 

 C:\DjangoProjects\mysite>python manage.py syncdb

http://stackoverflow.com/questions/4795045/django-syncdb-failes-when-adding-super-user-windows-7-mysql-django-1-2-4-mys 

-----------------------------------

Django is a free web framework written in python. It's very to use!

Let's create a blog in less then 10min!

1. First create a project

django-admin.py startproject blog

Switch to folder "blog"

Start the dev server

./manage runserver 8000

Type: http://127.0.0.1:8000 in browser


2. Create a file "models.py"

 Create a model

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

3. Setup your database settings

Edit the file "settings.py"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'test',                      # Or path to database file if using sqlite3.
        'USER': 'test',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

4. "Install" the blog models

Add "blog" to INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog', #<-------------------------------
    # Uncomment the next line to enable the admin:
    #'django.contrib.admin',
)

5. Create a templates

Create folder "templates".

Switch to folder "templates". Create file "index.html"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
    {% endblock %}
    </div>
</body>

</html
6. Setup the templates path
Edit "settings.py" file.
Import os at the top
Add path to TEMPLATES_DIRS
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__),'templates'), # creates a absolute path
)

7. Create the blog tables

Run "./manage syncdb"

It will create the blog tables.
It will ask you to create a superuser, follow the instructions

8. Add a url pattern

Edit file "urls.py"

urlpatterns = patterns('',
    # Example:
    # (r'^blog/', include('blog.foo.urls')),
    (r'^, 'blog.views.index'), #<------------------- index/root entry

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    #(r'^admin/', include(admin.site.urls)),
)

9. Create a view

Create a file "views.py"
from django.shortcuts import render_to_response

def index(request):
    return render_to_response('index.html', locals())

Run the dev server: ./manage runserver 8000


10. Activate the admin

Uncomment "django.contrib.admin" in INSTALLED_APPS
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin', #<<<------- uncommented
)

Edit "urls.py" file

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin #<<< uncomment this
admin.autodiscover() #<<< uncomment this

urlpatterns = patterns('',
    (r'^, 'blog.views.index'),
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)), #<<< uncomment this
)

Run ./manage syncdb

11. Activate the module in admin

Create file "admin.py"

from django.contrib import admin
from blog.models import Blog

class AdminBlog(admin.ModelAdmin):
    pass

admin.site.register(Blog, AdminBlog)

Type "http://127.0.0.1:8000/admin" in your browser

Login as superuser which you choose before


Click on "Add" and create some posts

12. Fill the view with logic

from django.shortcuts import render_to_response
from blog.models import Blog

def index(request):
    entries = Blog.objects.all()
    return render_to_response('index.html', locals())

13. Show it in template

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
        {% for e in entries %}
            {{ e.title }}<br/>
            {{ e.date }}<br/>
            {{ e.text }}<br/>
            <hr/>
        {% endfor %}

    {% endblock %}
    </div>
</body>

</html>
Type http://127.0.0.1:8000 in your browser and you see your blog!



-------------------------------------------------------------------------------------
Every view renders a webpage. For this Django has a own template system.
1. First we create a templates folder in our root project and change into it
2. Now create a folder what ever you like, the best would be the name of the application, like homepage and change into it
3. When create a index.html, to make clear that is the entry point of this application template
4. Create your our html template or for example:

<html>
<head>
    <title>My Blog Index</title>
</head>
<body>
    <h3>Index Page</h3>
</body>
</html>


5. Open the global settings
6. Import on the top the os module and modify the TEMPLATE_DIRS variable and add the path, for example
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
#....
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join( os.path.dirname(__file__), 'templates' ),)
#....

7. Open the views.py file
8. Import the render_to_response function. This will do the job for you, parse a template and return a valid HttpResponse object.
9. Use the render_to_response in the view, for example
from django.shortcuts import render_to_response
def index(request):
    return render_to_response('homepage/index.html')  
10. The first parameter is the template.
11. Start the dev server: python manage.py runserver



-------------



-------------------------------------------

http://geonode.readthedocs.org/en/latest/tutorials/devel/projects/apps.html#

Adding additional Django apps to your GeoNode Project

Since GeoNode is based on Django, your GeoNode project can be augmented and enhanced by adding additional third-party pluggable Django apps or by writing an app of your own.
This section of the workshop will introduce you to the Django pluggable app ecosystem, and walk you through the process of writing your own app and adding a blog app to your project.

Django pluggable apps

The Django app ecosystem provides a large number of apps that can be added to your project. Many are mature and used in many existing projects and sites, while others are under active early-stage development. Websites such as Django Packages provide an interface for discovering and comparing all the apps that can plugged in to your Django project. You will find that some can be used with very little effort on your part, and some will take more effort to integrate.

Adding your own Django app

Let’s walk through the an example of the steps necessary to create a very basic Django polling app to and add it to your GeoNode project. This section is an abridged version of the Django tutorial itself and it is strongly recommended that you go through this external tutorial along with this section as it provides much more background material and a signficantly higher level of detail. You should become familiar with all of the information in the Django tutorial as it is critical to your success as a GeoNode project developer.
Throughout this section, we will walk through the creation of a basic poll application. It will consist of two parts:
  • A public site that lets people view polls and vote in them.
  • An admin site that lets you add, change, and delete polls.
  1. Create app structure
    Since we have already created our GeoNode project from a template project, we will start by creating our app structure and then adding models:
    $ 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.
  2. Add models
    The next step in writing a database web app in Django is to define your models—essentially, your database layout with additional metadata.
    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')
        def __unicode__(self):
            return self.question
    
    class Choice(models.Model):
        poll = models.ForeignKey(Poll)
        choice = models.CharField(max_length=200)
        votes = models.IntegerField()
        def __unicode__(self):
            return self.choice
    
    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 <my_geonode>/settings.py file, and update the INSTALLED_APPS setting to include the string “polls”. So it will look like this:
    INSTALLED_APPS = (
    
        # Apps bundled with Django
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.admin',
        'django.contrib.sitemaps',
        'django.contrib.staticfiles',
        'django.contrib.messages',
        'django.contrib.humanize',
    
        #Third party apps
    
        # <snip>
    
        # GeoNode internal apps
        'geonode.maps',
        'geonode.upload',
        'geonode.layers',
        'geonode.people',
        'geonode.proxy',
        'geonode.security',
        'geonode.search',
        'geonode.catalogue',
        'geonode.documents',
    
        # My GeoNode apps
        'polls',
    )
    
    Now Django knows to include the polls app. Let’s run another command:
    $ 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’ve 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.
    GeoNode uses south for migrations ...
  3. Add Django Admin Configuration
    Next, let’s add the Django admin configuration for our polls app so that we can use the Django Admin to manage the records in our database. Create and edit a new file called polls/admin.py and make it look like the this:
    from polls.models import Poll
    from django.contrib import admin
    
    admin.site.register(Poll)
    
    Run the development server and explore the polls app in the Django Admin by pointing your browser to http://localhost:8000/admin/ and logging in with the credentials you specified when you first ran syncdb.
    ../../../_images/admin_top.png
    You can see all of the other apps that are installed as part of your GeoNode project, but we are specifically interested in the Polls app for now.
    ../../../_images/admin_polls.png
    Next we will add a new poll via automatically generated admin form.
    ../../../_images/add_new_poll.png
    You can enter any sort of question you want for initial testing and select today and now for the publication date.
    ../../../_images/add_poll.png
  4. Configure Choice model
    The next step is to configure the Choice model in the admin, but we will configure the choices to be editable in-line with the Poll objects they are attached to. Edit the same polls/admin.py so it now looks like the following:
    from polls.models import Poll, Choice
    from django.contrib import admin
    
    class ChoiceInline(admin.StackedInline):
        model = Choice
        extra = 3
    
    class PollAdmin(admin.ModelAdmin):
        fieldsets = [
            (None,               {'fields': ['question']}),
            ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
        ]
        inlines = [ChoiceInline]
    
    admin.site.register(Poll, PollAdmin)
    
    This tells Django that Choice objects are edited on the Poll admin page, and by default, provide enough fields for 3 choices.
  5. Add/edit poll
    You can now return to the Poll admin and either add a new poll or edit the one you already created and see that you can now specify the poll choices inline with the poll itself.
    ../../../_images/choice_admin.png
  6. Create views
    From here, we want to create views to display the polls inside our GeoNode project. A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template. In our poll application, there will be the following four views:
    • Poll “index” page—displays the latest few polls.
    • Poll “detail” page—displays a poll question, with no results but with a form to vote.
    • Poll “results” page—displays results for a particular poll.
    • Vote action—handles voting for a particular choice in a particular poll.
    The first step of writing views is to design your URL structure. You do this by creating a Python module called a URLconf. URLconfs are how Django associates a given URL with given Python code.
    Let’s start by adding our URL configuration directly to the urls.py that already exists in your project at <my_geonode>/urls.py. Edit this file and add the following lines after the rest of the existing imports around line 80:
    url(r'^polls/$', 'polls.views.index'),
    url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'),
    url(r'^polls/(?P<poll_id>\d+)/results/$', 'polls.views.results'),
    url(r'^polls/(?P<poll_id>\d+)/vote/$', 'polls.views.vote'),
    
    Note
    Eventually we will want to move this set of URL configurations inside the URLs app itself, but for the sake of brevity in this workshop, we will put them in the main urls.py for now. You can consult the Django tutorial for more information on this topic.
    Next write the views to drive the URL patterns we configured above. Edit polls/views.py to that it looks like the following:
    from django.template import RequestContext, loader
    from polls.models import Poll
    from django.http import HttpResponse
    from django.http import Http404
    from django.shortcuts import render_to_response
    
    def index(request):
        latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
        return render_to_response('polls/index.html',
            RequestContext(request, {'latest_poll_list': latest_poll_list}))
    
    def detail(request, poll_id):
        try:
            p = Poll.objects.get(pk=poll_id)
        except Poll.DoesNotExist:
            raise Http404
        return render_to_response('polls/detail.html', RequestContext(request, {'poll': p}))
    
    def results(request, poll_id):
        return HttpResponse("You're looking at the results of poll %s." % poll_id)
    
    def vote(request, poll_id):
        return HttpResponse("You're voting on poll %s." % poll_id)
    
    Note
    We have only stubbed in the views for the results and vote pages. They are not very useful as-is. We will revisit these later.
    Now we have views in place, but we are referencing templates that do not yet exist. Let’s add them by first creating a template directory in your polls app at polls/templates/polls and creating polls/templates/polls/index.html to look like the following:
    {% if latest_poll_list %}
        <ul>
        {% for poll in latest_poll_list %}
            <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>No polls are available.</p>
    {% endif %}
    
    Next we need to create the template for the poll detail page. Create a new file at polls/templates/polls/detail.html to look like the following:
    <h1>{{ poll.question }}</h1>
    <ul>
    {% for choice in poll.choice_set.all %}
        <li>{{ choice.choice }}</li>
    {% endfor %}
    </ul>
    
    You can now visit http://localhost:8000/polls/ in your browser and you should see the the poll question you created in the admin presented like this.
    ../../../_images/polls_plain.png
  7. Update templates
    We actually want our polls app to display as part of our GeoNode project with the same theme, so let’s update the two templates we created above to make them extend from the site_base.html template we looked at in the last section. You will need to add the following two lines to the top of each file:
    {% extends 'site_base.html' %}
    {% block body %}
    
    And close the block at the bottom of each file with:
    {% endblock %}
    
    This tells Django to extend from the site_base.html template so your polls app has the same style as the rest of your GeoNode, and it specifies that the content in these templates should be rendered to the body block defined in GeoNode’s base.html template that your site_base.html extends from.
    You can now visit the index page of your polls app and see that it is now wrapped in the same style as the rest of your GeoNode site.
    ../../../_images/polls_geonode.png
    If you click on a question from the list you will be taken to the poll detail page.
    ../../../_images/poll_geonode_hidden.png
    It looks like it is empty, but in fact the text is there, but styled to be white by the Bootswatch theme we added in the last section. If you highlight the area where the text is, you will see that it is there.
    ../../../_images/poll_geonode_highlight.png
Now that you have walked through the basic steps to create a very minimal (though not very useful) Django app and integrated it with your GeoNode project, you should pick up the Django tutorial at part 4 and follow it to add the form for actually accepting responses to your poll questions.
We strongly recommend that you spend as much time as you need with the Django tutorial itself until you feel comfortable with all of the concepts. They are the essential building blocks you will need to extend your GeoNode project by adding your own apps.

Adding a 3rd party blog app

Now that we have created our own app and added it to our GeoNode project, the next thing we will work through is adding a 3rd party blog app. There are a number of blog apps that you can use, but for purposes of this workshop, we will use a relatively simple, yet extensible app called Zinnia. You can find out more information about Zinnia on its website or on its GitHub project page or by following its documentation. This section will walk you through the minimal set of steps necessary to add Zinnia to your GeoNode project.
  1. Install Zinnia
    The first thing to do is to install Zinnia into the virtualenv that you are working in. Make sure your virtualenv is activated and execute the following command:
    $ pip install django-blog-zinnia
    
    This will install Zinnia and all of the libraries that it depends on.
  2. Add Zinnia to INSTALLED_APPS
    Next add Zinnia to the INSTALLED_APPS section of your GeoNode projects settings.py file by editing <my_geonode>/settings.py and adding ‘django.contrib.comments’ to the section labeled “Apps Bundled with Django” so that it looks like the following:
    # Apps bundled with Django
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'django.contrib.sitemaps',
    'django.contrib.staticfiles',
    'django.contrib.messages',
    'django.contrib.humanize',
    'django.contrib.comments',
    
    And then add the tagging, mptt and zinnia apps to the end of the INSTALLED_APPS where we previously added a section labeled “My GeoNode apps”. It should like like the following:
    # My GeoNode apps
    'polls',
    'tagging',
    'mptt',
    'zinnia',
    
  3. Synchronize models
    Next you will need to run syncdb again to synchronize the models for the apps we have just added to our project’s database. This time we want to pass the --all flag to syncdb so it ignores the schema migrations. Schema migrations are discussed further in GeoNode’s documentation, but it is safe to ignore them here.
    $ python manage.py syncdb --all
    
    You can now restart the development server and visit the Admin interface and scroll to the very bottom of the list to find a section for Zinnia that allows you to manage database records for Categories and Blog Entries.
    ../../../_images/zinnia_admin.png
  4. Configure project
    Next we need to configure our project to add Zinnia’s URL configurations. Add the following two URL configuration entries to the end of <my_geonode>/urls.py:
    url(r'^blog/', include('zinnia.urls')),
    url(r'^djcomments/', include('django.contrib.comments.urls')),
    
    If you visit the main blog page in your browser at http://localhost:8000/blog/ you will find that the blog displays with Zinnia’s default theme as shown below.
    Note
    If you are not able to visit the main blog page, you will have to set USE_TZ = True in settings.py. Restart the server and try again!
    ../../../_images/zinnia_default.png
    This page includes some guidance for us on how to change the default theme.
  5. Change default theme
    The first thing we need to do is to copy Zinnia’s base.html template into our own project so we can modify it. When you installed Zinnia, templates were installed to /var/lib/geonode/lib/python2.7/site-packages/zinnia/templates/zinnia/. You can copy the base template by executing the following commands:
    $ mkdir <my_geonode>/templates/zinnia
    $ cp /var/lib/geonode/lib/python2.7/site-packages/zinnia/templates/zinnia/base.html <my_geonode>/templates/zinnia/
    
    Then you need to edit this file and change the topmost line to read as below such that this template extends from our projects site_base.html rather than the zinnia skeleton.html:
    {% extends "site_base.html" %}
    
    Since Zinnia uses a different block naming scheme than GeoNode does, you need to add the following line to the bottom of your site_base.html file so that the content block gets rendered properly:
    {% block body %}{% block content %}{% endblock %}{% endblock %}
    
    ../../../_images/zinnia_geonode.png
    You can see that there are currently no blog entries, so let’s add one. Scroll to the bottom of the interface and click the Post an Entry link to go to the form in the Admin interface that lets you create a blog post. Go ahead and fill out the form with some information for testing purposes. Make sure that you change the Status dropdown to “published” so the post shows up right away.
    ../../../_images/zinnia_create_post.png
    You can explore all of the options available to you as you create your post, and when you are done, click the Save button. You will be taken to the page that shows the list of all your blog posts.
    ../../../_images/zinnia_post_list.png
    You can then visit your blog post/entry at http://localhost:8000/blog/.
    ../../../_images/zinnia_blog.png
    And if you click on the blog post title, you will be taken to the page for the complete blog post. You and your users can leave comments on this post and various other blog features from this page.
    ../../../_images/zinnia_post.png
  6. Integrate app into your site
    The last thing we need to do to fully integrate this blog app (and our polls app) into our site is to add it to the options on the navbar. To do so, we need to add the following block override to our Projects site_base.html:
    {% block extra-nav %}
    <li id="nav_polls">
        <a href="/polls/">Polls</a>
    </li>
    <li id="nav_blog">
        <a href="{% url 'zinnia_entry_archive_index' %}">Blog</a>
    </li>
    {% endblock %}
    
    ../../../_images/navbar_add.png
At this point, you could explore options for tighter integration between your GeoNode project and Zinnia. Integrating blog posts from Zinnia into your overall search could be useful, as well as including the blog posts a user has written on their Profile Page. You could also explore the additional plugins that go with Zinnia.

Adding other apps