In this post I am going to demonstrate how to develop basic and very first website using Django - A Python Web Framework. First of all, You need to have Python and Django installed on your machine. In my previous post I have already explained how to install Django on both Linux and Windows. After installation is completed, you can start your first project.
For better understanding create new directory for Django(just for convenience). To start project run django-admin.py startproject firstproject command in your working directory. ("firstproject" is just a name of Project, you can replace it with any name).
It will create project directory named firstproject. There will be two directory, Outer firstproject and Inner firstproject. If you are using Linux you have to change permission of every single file and directory. To do this, Goto firstproject directory and run chmod 777 * command.Again goto inner firstproject directory and run the same command.
Outer firstproject directory contains manage.py and inner firstproject directory.
manage.py is a command line utility. you can run python manage.py help commnad for help.
Inner firstproject directory contains another four files.
Now we will create our first module. Create file named views.py in the Inner firstproject diretory. You can give any name to this file but, it is good convention to call it views.py.
Write the following code in this file.(line starting with '#' is comment line)
Now we have written simple module, But our Django project do not about module we've just created. To explicitly join this module with our project we have to assign particular URL to this module.
To configure URL open urls.py file, which resides in inner firstproject directory.
If we remove comments line it only contains following:
Now to configure our module, we will add url(r'^first_project$',first_project) line as argument to patterns function. Code will look something like this.
First argument to URL is Regular Expression and Second argument is name of function we want to call when URL is opened.
For basic understanding of Regular Expression,
- '^' sign will match staring with first_project/(e.g. first_project/first, first_project/help etc.)
- '$' sign will match ending with first_project/(e.g. .../first/first_project/, .../help/first_project/ etc.)
After this our basic project is done. To run it, we have to start Django server.
- Change to outer firstproject directory
- run python manage.py runserver command. By default it runs our server on 8000 port.
- Now open Web Browser and type 127.0.0.1:8000 in addressbar.
If every thing works fine, You should see output "Welcome to my First Project". That's it !! this is your first Web application/Web Site using Django Framework.
Here we have simply returned plain text as response. But for real web site you have HTML code to be rendered on your page.
Tidak ada komentar:
Posting Komentar