Search Google

Sunday 19 April 2015

How does Python work?





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
 Learn Python in 5 min

http://www.quora.com/How-do-I-find-a-good-Django-tutorial-for-beginners

Installation

Via Laravel Installer

First, download the Laravel installer using Composer.
composer global require "laravel/installer=~1.1"
Make sure to place the ~/.composer/vendor/bin directory in your PATH (or C:\%HOMEPATH%\AppData\Roaming\Composer\vendor\bin if working with Windows) so the laravel executable is found when you run the laravel command in your terminal.
Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog would create a directory named blog containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer.

Via Composer

The Laravel framework utilizes Composer for installation and dependency management. If you haven't already, start by installing Composer.
Now you can install Laravel by issuing the following command from your terminal:
composer create-project laravel/laravel your-project-name --prefer-dist
This command will download and install a fresh copy of Laravel in a new your-project-name folder within your current directory.
If you prefer, you can alternatively download a copy of the Laravel repository from GitHub manually. Next run the composer install command in the root of your manually created project directory. This command will download and install the framework's dependencies.

Permissions

After installing Laravel, you may need to grant the web server write permissions to the app/storage directories. See the Installation documentation for more details on configuration.

Serving Laravel

Typically, you may use a web server such as Apache or Nginx to serve your Laravel applications. If you are on PHP 5.4+ and would like to use PHP's built-in development server, you may use the serve Artisan command:
php artisan serve
By default the HTTP-server will listen to port 8000. However if that port is already in use or you wish to serve multiple applications this way, you might want to specify what port to use. Just add the --port argument:
php artisan serve --port=8080

Directory Structure

After installing the framework, take a glance around the project to familiarize yourself with the directory structure. The app directory contains folders such as views, controllers, and models. Most of your application's code will reside somewhere in this directory. You may also wish to explore the app/config directory and the configuration options that are available to you.

Local Development Environment

In the past, configuring a local PHP development environment on your machine was a headache. Installing the proper version of PHP, required extensions, and other needed components is time consuming and confusing. Instead, consider using Laravel Homestead. Homestead is a simple virtual machine designed for Laravel and Vagrant. Since the Homestead Vagrant box is pre-packaged with all of the software you need to build robust PHP applications, you can create a virtualized, isolated development environment in seconds. Here is a list of some of the goodies included with Homestead:
  • Nginx
  • PHP 5.6
  • MySQL
  • Redis
  • Memcached
  • Beanstalk
Don't worry, even though "virtualized" sounds complicated, it's painless. VirtualBox and Vagrant, which are Homestead's two dependencies, both include simple, graphical installers for all popular operating systems. Check out the Homestead documentation to get started.

Routing

To get started, let's create our first route. In Laravel, the simplest route is a route to a Closure. Pop open the app/routes.php file and add the following route to the bottom of the file:
Route::get('users', function()
{
    return 'Users!';
});
Now, if you hit the /users route in your web browser, you should see Users! displayed as the response. Great! You've just created your first route.
Routes can also be attached to controller classes. For example:
Route::get('users', 'UserController@getIndex');
This route informs the framework that requests to the /users route should call the getIndex method on the UserController class. For more information on controller routing, check out the controller documentation.

Creating A View

Next, we'll create a simple view to display our user data. Views live in the app/views directory and contain the HTML of your application. We're going to place two new views in this directory: layout.blade.php and users.blade.php. First, let's create our layout.blade.php file:
<html>
    <body>
        <h1>Laravel Quickstart</h1>

        @yield('content')
    </body>
</html>
Next, we'll create our users.blade.php view:
@extends('layout')

@section('content')
    Users!
@stop
Some of this syntax probably looks quite strange to you. That's because we're using Laravel's templating system: Blade. Blade is very fast, because it is simply a handful of regular expressions that are run against your templates to compile them to pure PHP. Blade provides powerful functionality like template inheritance, as well as some syntax sugar on typical PHP control structures such as if and for. Check out the Blade documentation for more details.
Now that we have our views, let's return it from our /users route. Instead of returning Users! from the route, return the view instead:
Route::get('users', function()
{
    return View::make('users');
});
Wonderful! Now you have setup a simple view that extends a layout. Next, let's start working on our database layer.

Creating A Migration

To create a table to hold our data, we'll use the Laravel migration system. Migrations let you expressively define modifications to your database, and easily share them with the rest of your team.
First, let's configure a database connection. You may configure all of your database connections from the app/config/database.php file. By default, Laravel is configured to use MySQL, and you will need to supply connection credentials within the database configuration file. If you wish, you may change the driver option to sqlite and it will use the SQLite database included in the app/database directory.
Next, to create the migration, we'll use the Artisan CLI. From the root of your project, run the following from your terminal:
php artisan migrate:make create_users_table
Next, find the generated migration file in the app/database/migrations folder. This file contains a class with two methods: up and down. In the up method, you should make the desired changes to your database tables, and in the down method you simply reverse them.
Let's define a migration that looks like this:
public function up()
{
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('email')->unique();
        $table->string('name');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('users');
}
Next, we can run our migrations from our terminal using the migrate command. Simply execute this command from the root of your project:
php artisan migrate
If you wish to rollback a migration, you may issue the migrate:rollback command. Now that we have a database table, let's start pulling some data!

Eloquent ORM

Laravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.
First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the app/models directory. Let's define a User.php model in that directory like so:
class User extends Eloquent {}
Note that we do not have to tell Eloquent which table to use. Eloquent has a variety of conventions, one of which is to use the plural form of the model name as the model's database table. Convenient!
Using your preferred database administration tool, insert a few rows into your users table, and we'll use Eloquent to retrieve them and pass them to our view.
Now let's modify our /users route to look like this:
Route::get('users', function()
{
    $users = User::all();

    return View::make('users')->with('users', $users);
});
Let's walk through this route. First, the all method on the User model will retrieve all of the rows in the users table. Next, we're passing these records to the view via the with method. The with method accepts a key and a value, and is used to make a piece of data available to a view.
Awesome. Now we're ready to display the users in our view!

Displaying Data

Now that we have made the users available to our view, we can display them like so:
@extends('layout')

@section('content')
    @foreach($users as $user)
        <p>{{ $user->name }}</p>
    @endforeach
@stop
You may be wondering where to find our echo statements. When using Blade, you may echo data by surrounding it with double curly braces. It's a cinch. Now, you should be able to hit the /users route and see the names of your users displayed in the response.
This is just the beginning. In this tutorial, you've seen the very basics of Laravel, but there are so many more exciting things to learn. Keep reading through the documentation and dig deeper into the powerful features available to you in Eloquent and Blade. Or, maybe you're more interested in Queues and Unit Testing. Then again, maybe you want to flex your architecture muscles with the IoC Container. The choice is yours!

Deploying Your Application

One of Laravel's goals is to make PHP application development enjoyable from download to deploy, and Laravel Forge provides a simple way to deploy your Laravel applications onto blazing fast servers. Forge can configure and provision servers on DigitalOcean, Linode, Rackspace, and Amazon EC2. Like Homestead, all of the latest goodies are included: Nginx, PHP 5.6, MySQL, Postgres, Redis, Memcached, and more. Forge "Quick Deploy" can even deploy your code for you each time you push changes out to GitHub or Bitbucket!
On top of that, Forge can help you configure queue workers, SSL, Cron jobs, sub-domains, and more. For more information, visit the Forge website.
.........................................................................................................................................

All the Blade Template Commands

  • {{ $var }} – Echo content
  • {{ $var or 'default' }} – Echo content with a default value
  • {{{ $var }}} – Echo escaped content
  • {{-- Comment --}} – A Blade comment
  • @extends('layout') – Extends a template with a layout
  • @if(condition) – Starts an if block
  • @else – Starts an else block
  • @elseif(condition) – Start a elseif block
  • @endif – Ends a if block
  • @foreach($list as $key => $val) – Starts a foreach block
  • @endforeach – Ends a foreach block
  • @for($i = 0; $i < 10; $i++) – Starts a for block
  • @endfor – Ends a for block
  • @while(condition) – Starts a while block
  • @endwhile – Ends a while block
  • @unless(condition) – Starts an unless block
  • @endunless – Ends an unless block
  • @include(file) – Includes another template
  • @include(file, ['var' => $val,...]) – Includes a template, passing new variables.
  • @each('file',$list,'item') – Renders a template on a collection
  • @each('file',$list,'item','empty') – Renders a template on a collection or a different template if collection is empty.
  • @yield('section') – Yields content of a section.
  • @show – Ends section and yields its content
  • @lang('message') – Outputs message from translation table
  • @choice('message', $count) – Outputs message with language pluralization
  • @section('name') – Starts a section
  • @stop – Ends section
  • @endsection – Ends section
  • @append – Ends section and appends it to existing of section of same name
  • @overwrite – Ends section, overwriting previous section of same name\
.................................................................................................................
So to start.. we want to add/edit the content of our homepage. We can do this by going in to /app/routes.php. You will see that currently the route is hardcoded to return View::make('hello'). We could then simply change the view file.. but long term this just isn't going to fly. So comment this out (for the purpose of the tutorial - later you could remove completely) and add return HomeController::showWelcome(). You should now have something that looks like this:
1.Route::get('/', function()
2.{
3.return HomeController::showWelcome();
4.//return View::make('hello');
5.});
Now we're pointing the page to our controller HomeController... that you will find inside /app/controllers. We've now got better control on our content.
To start with now, we will set our logic inside the controller - but later in the tutorial we will move this in to a model.
Change your showWelcome method to this:
01.public static function showWelcome()
02.{
03. 
04.//$cheese = Test::getCheese();
05. 
06.$data   = array(
07. 
08.'cheese' => 'cheese value'
09.);
10. 
11.return View::make('hello', $data);
12.}
What is going on here?
OK.. so the first bit... ignore the commented out line for now.. we will come back to it.
The array called $data... this is where we can set all data that is passed to the view file. And you can see that for now I've hardcoded the value of 'cheese' to 'cheese value'... we will move this over to the model shortly.
Finally, we now tell the method to return a view, and we pass in to it our $data array.
If we go in to /app/views/hello.php now... you can add a echo $cheese; statement somewhere amongst the main html content (obviously wrapped in PHP tags). And now when you refresh yourdomain.com/public you should see the usual splash page.. but now with added cheese.
OK.. so we're in a much stronger position now... but now we want to ensure that our business logic is performed outside of the controller... as we don't want big fat ugly controllers.
We're now going to set it so that cheese value is returned from a model. So to start create a new file called Test.php inside of /app/models and then add this code to it:
01.class Test {
02. 
03. 
04.public static function getCheese() {
05. 
06.return "cheeeese";
07.}
08. 
09.}
Obviously in reality this would be a very poor method... but it's merely serving a point here. So this method returns a string of "cheeeese".
If we now go back to our controller HomeController.php, uncomment the uncommented line $cheese = Test::getCheese(); ... then change 'cheese value' to the var $cheese... like so:
1.$data   = array(
2. 
3.'cheese' => $cheese
4.);
If you refresh the page now you should see that our value is now coming in from our model.
That concludes this basic tutorial... obviously there is a lot more to learn about Laravel, but this tutorial at least (I hope) shows you how to setup a very basic page in Laravel.
Thanks for reading!

.............................................................................................
This tutorial will walk us through:
  • Creating a users table using migrations
  • Filling our new users table with sample users using seeding
  • Using the great artisan command line tool to migrate and seed
  • Creating a login form and processing a login using routes, controllers, and views
  • Handling login errors
  • Use Eloquent ORM to validate a user

Getting our Database Ready

To get our authentication working, we will need to have a database and users to login with.

Database Setup

Set up your database and user. Assign that user to the database and make sure you update your settings in app/config/database.php.

Migrations

Migrations are a way we can manipulate our database within our codebase. This means we don’t have to get our hands dirty by doing any SQL commands or messing around inside a tool like phpmyadmin. For more information and the benefits of migrations, see the official docs.
Migrations are very easy to create. The easiest way to create a migration will be to use the great artisan command line interface created by Taylor Otwell. To create the migration, via the command line, in the root folder of your application, simply type:
php artisan migrate:make create_users_table ––create=users
This will automatically create a migrations file inside of your app/database/migrations folder. Let’s take a look at the newly created file.
// app/database/migrations/####_##_##_######_create_users_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
      Schema::create('users', function(Blueprint $table)
      {
          $table->increments('id');
          $table->timestamps();
      });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
      //
  }

}

Laravel generates the core of the migration file for you and the –create command will let the migration create the table for you. It will create a table for you with an id field and the timestamps field. This will make created_at and updated_at fields. Now we use the Schema Builder to create our users table.
// app/database/migrations/####_##_##_######_create_users_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
      Schema::create('users', function(Blueprint $table)
      {
          $table->increments('id');

          $table->string('name', 32);
          $table->string('username', 32);
          $table->string('email', 320);
          $table->string('password', 64);

                      // required for Laravel 4.1.26
                      $table->string('remember_token', 100)->nullable();
          $table->timestamps();
      });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
      Schema::drop('users');
  }

}

Now this migration file will be responsible for creating the users table and also destroying it if needed. To run the migration and create our user table, use the command line again and run:
php artisan migrate
Just like that, the command will use the up() function and bam! We have our users table with all the columns we wanted.
Reverting Migrations: Now if you wanted to rollback migrations, we could use php artisan migrate:rollback or php artisan migrate:reset.
Now that we have our table, lets create sample users.

Seeding

Seeding is the technique of filling our database with sample data so we can test and create our applications. It really does make building applications much easier. For seeder files, we won’t be using artisan. We’ll make these the good old fashioned way… New file. In your app/database/seeds folder, create a file called UserTableSeeder.php.
// app/database/seeds/UserTableSeeder.php

<?php

class UserTableSeeder extends Seeder
{

public function run()
{
    DB::table('users')->delete();
    User::create(array(
        'name'     => 'Chris Sevilleja',
        'username' => 'sevilayha',
        'email'    => '',
        'password' => Hash::make('awesome'),
    ));
}

}

We will create a user and all of the above is pretty self explanatory aside from password. We will use Laravel’s Hash class to create a secure Bcrypt hashing of our password. This is always a good practice to hash our password and to read more about Laravel security, check out the docs. Now that we have created our file, we need to Laravel to call it. Inside the app/database/seeds/DatabaseSeeder.php, add the line $this->call('UserTableSeeder');.
// app/database/seeds/DatabaseSeeder.php

<?php

class DatabaseSeeder extends Seeder {

  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
      Eloquent::unguard();

      $this->call('UserTableSeeder');
  }

}

Once we’re done with our seeder file, we can inject that user into our database using:
php artisan db:seed

The Application

Now that we have a database, a table thanks to migrations, and a user thanks to seeding, we can build the authentication system. We will need to create routes, controllers, and views for our form.

Routes

In Laravel, our routes file dictates the lay of the land in our application. We will define 2 routes for our login, one for the http get to show the form, and one for the http post request to process the form. Laravel let’s us define routes based on HTTP request types and this helps to organize our application and how a user interacts around the site. For more info on this: show link. Add the following routes we need in our app/routes.php file:
// app/routes.php

<?php

// route to show the login form
Route::get('login', array('uses' => ''));

// route to process the form
Route::post('login', array('uses' => ''));

Now if we go to our application in our browser and go to www.example.com/login, we will get an error because we haven’t defined the HomeController@showLogin function yet. Let’s do that.

Controller

In our app/controllers directory, Laravel should already come with a HomeController.php and a BaseController.php. Inside our HomeController.php, we are going to create the two functions we need. Add these two.
// app/controllers/HomeController.php<

...

public function showLogin()
{
    // show the form
    return View::make('login');
}

public function doLogin()
{
// process the form
}
For now, we will only deal with the function to show the form.

View

The easiest part of this process will be creating our login view. In the app/views folder, create a file called login.blade.php. The .blade.php extension lets Laravel know that we will be using its Blade Templating system.
<!-- app/views/login.blade.php --><

<!doctype html>
<html>
<head>
<title>Look at me Login</title>
</head>
<body><

{{ Form::open(array('url' => 'login')) }}
<h1>Login</h1>

<!-- if there are login errors, show them here -->
<p>
    {{ $errors->first('email') }}
    {{ $errors->first('password') }}
</p>

<p>
    {{ Form::label('email', 'Email Address') }}
    {{ Form::text('email', Input::old('email'), array('placeholder' => '')) }}
</p>

<p>
    {{ Form::label('password', 'Password') }}
    {{ Form::password('password') }}
</p>

<p>{{ Form::submit('Submit!') }}</p>
{{ Form::close() }}

When someone submits the form, it posts to the HomeController@doLogin function. Let’s validate the information and process the form.
If there are validation errors, they will be redirected here and the email input will already be filled in with their old input. Errors will also show if there are any.

Processing the Form

Back in our HomeController.php, let’s build out our doLogin() function. We have to validate the information sent to make sure that we have an email and a password. Both fields are required.
// app/controllers/HomeController.php<


public function doLogin()
{
// validate the info, create rules for the inputs
$rules = array(
    'email'    => 'required|email', // make sure the email is an actual email
    'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);

// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);

// if the validator fails, redirect back to the form
if ($validator->fails()) {
    return Redirect::to('login')
        ->withErrors($validator) // send back all errors to the login form
        ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {

    // create our user data for the authentication
    $userdata = array(
        'email'     => Input::get('email'),
        'password'  => Input::get('password')
    );

    // attempt to do the login
    if (Auth::attempt($userdata)) {

        // validation successful!
        // redirect them to the secure section or whatever
        // return Redirect::to('secure');
        // for now we'll just echo success (even though echoing in a controller is bad)
        echo 'SUCCESS!';

    } else {        

        // validation not successful, send back to form 
        return Redirect::to('login');

    }

}
}
We use the Auth class to authenticate a user. Auth::attempt() will check the plaintext password against the hashed password we saved in our database.
Try the login: Let’s try to login with whatever we put in our app/database/UserTableSeeder.php file. In our case:
Email Password
chris@scotch.io awesome
If the authentication is successful (Auth::attempt() returns true), we will redirect the user to wherever they should go. After they are logged in, that users information is saved and can be accessed using Auth::user()->email;. If the authentication is not successful, we will be kicked back to the login form with errors and the old email input to populate the form.

Logout

Logging out is a simple matter. We’ll need a new route and a new function.
Add this route for logout.
// app/routes.php
...
Route::get('logout', array('uses' => ''));
...
 
Ideally, this route would be a POST route for security purposes. This will ensure that your logout won’t be accidentally triggered. http://stackoverflow.com/questions/3521290/logout-get-or-post Also, to handle this as a POST, you will have to handle your link differently. You’ll have to create a POST request to your logout route.
For logout, we will flush and clean out the session and then redirect our user back to the login screen. You can change this to redirect a user wherever you would like. A home page or even a sad goodbye page.
// app/controllers/HomeController.php
public function doLogout()
{
    Auth::logout(); // log the user out of our application
    return Redirect::to('login'); // redirect the user to the login screen
}
 
Now that you have the route and the function, you can create a logout button by using the Laravel URL helper.
<!-- LOGOUT BUTTON -->
<a href="{{ URL::to('logout') }}">Logout</a>
 

Bam!

Now going to your login page, www.example.com/login and submitting the login form will provide validation, authentication against a user in the database, and a little more understanding of how Laravel makes things like building an authentication system easier. We’ll be doing a lot more writeups on Laravel, so sound off in the comments if you have questions or anything else you want to see.
Edit Updated the doLogin() function and the view to pass back errors and handle Auth correctly with Hash::check(). Edit #2 Changed back to the Auth::attempt() login method. Edit #3 Cleaned up and commented code examples. Provided code for download. Edit #4 Added logout. Edit #5 Upgraded user migration to work with Laravel 4.1.26 
----------------------------------------------------------------

Q.....This question may seems a little bit silly, but what the heck.
I started to learn Python. I know basic syntax, etc.
When I work with HTML, PHP, etc., I simply write code, put it inside .html or .php file and double click this file. Then my code runs. I can work with databases and other stuff - it's just simple. But how does Python work? I'm working inside Eclipse or Python command line and I can run this code, but what if I want make website with Python for example?
I don't think it's like I put .py file on my server, so what I need to do? I understand I need to install Python on my webserver through some server command line (I've never used it, but I will find some tutorials day I will need it) but what's next? How can I combine my Python knowledge with HTML, CSS, PHP, etc.?
Python may also be used to create desktop apps, what then? Can I export .exe file with Python code or what?
Any links with content describing my concerns are welcome!

 http://programmers.stackexchange.com/questions/107922/how-does-python-work
ANS.................

When I work with HTML, PHP, etc., I simply write code, put it inside .html or .php file and double click this file. Then my code runs.
But how does Python work?
Exactly the same way.
Double-click a .py file and your code runs.
I'm working inside Eclipse or Python command line and I can run this code, but what if I want make website with Python for example?
You usually use Apache to host a web site. You usually use mod_wsgi to run Python inside Apache. This is exactly like using mod_php to run PHP inside Apache.
Exactly the same.
I don't think it's like I put .py file on my server,
False. You do put .py files on your server. How else could it possibly work?
so what I need to do? I understand I need to install Python on my webserver through some server command line (I've never used it, but I will find some tutorials day I will need it) but what's next?
You need mod_php to run PHP. You need mod_wsgi to run Python.

So if I made some website with Python, then my user will see my index.py file when he comes to my server?
You could do that. It would be fairly silly, however.
Usually, you set up mod_wsgi so that it executes your .py file, and your .py file creates the HTML page.
This parallels the way mod_php executes the .php file to create an HTML page.
Or can I use Python code inside html like with php wrapped inside <?php ?>?
No. You put the HTML inside the Python.


How can I combine my Python knowledge with html, css, php etc?
Use a web framework that supports Python, such as Django.
Python may also be used to create desktop apps, what then? Can I export .exe file with Python code or what?
Python is typically executed by an interpreter, so it's easy to use interactively and you can see results of your changes almost immediately. A Python program can also be packaged up into a stand-alone executable; more on how to do that here.


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!

We are done!

No comments:

Post a Comment