免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2133 | 回复: 0
打印 上一主题 下一主题

Introduction to Django [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-04-06 16:13 |只看该作者 |倒序浏览

Django is opensource Web framework written in Python. Django loosely follows MVC design pattern. Django being written in Python you should have some knowledge of Python. You can download Django from
http://www.djangoproject.com/download
. I have been using Django since its 0.96 release. Today I decided to write a small application using it.
As Django follows design pattern similar to MVC lets first understand what MVC is:
MVC Design Pattern

There are various MVC frameworks available like CakePHP, Zend Framework for PHP developers, Struts for Java developers, Catalyst for Perl developers and Rails for Ruby developers.
Model
Model is generally used to interact with the databases. Suppose you are working on some social networking site and you want to get user’s friends list. All the queries regarding this is written in Models. The resultant output is passed on to Controller.
Controller
All the business logic goes here. Consider the same scenario where user wants to get his own friends list. At this time Controller will get some inputs from user. Inputs may be number of friends he wants to see at a time or may be the number of users from India. Based on the user inputs the Controller with interact with Model to get the friends list. And then the list is passed to View.
View
View are used for creating User Interface. In our case User Interface will be based on the friends list recieved from Controller. View will take care of how the list is going to be displayed and what details are to be displayed.
MVC pattern allows us the write the code which is easier to maintain, Programmer writes Model and Controller and at the same time Designer can create View. And also few changes somewhere wont affect the entire system. We can say that MVC applications are loosely coupled.
Django follows slightly modified version of MVC design pattern called MTV design pattern. MTV stands for Model-Template-View. Now lets see how Django’s MTV pattern is:
MTV Design Pattern
Model
A Model in Django is a Python class which represents a table from database. You dont need to write complex SQL queries to get records from Database. You can do it by writing Python code itself.
View
In Django views contains all business logic code.
Template
These are the HTML pages which create User Interface. Django comes with very powerfull templating system.
Get Set Code..
Now its time to create our application. The application will be a simple address book. We will make use of Django’s Admin to add records and will create a view to display the contacts in address book.
Lets create a new Django project. Run the following command:
view plain
copy to clipboard
print
?
  
$ django-admin.py startproject djangoapp  $ django-admin.py startproject djangoapp
A new directory called list will be created which contains following files:  
__init__.py: So that Python treats this directory as package.
manage.py: Command line utility to interact with our project.
settings.py: Configuration file for our project.
urls.py: URL mappings of our project.
Django comes with light weight Web server. DONT USE IT FOR PRODUCTION. Next
view plain
copy to clipboard
print
?
  
$ cd djangoapp  $ cd djangoapp
And boot the webserver:
view plain
copy to clipboard
print
?
  
$ django-admin.py manage.py runserver  $ django-admin.py manage.py runserver
This will start Web server on port 8000(default). Visit
http://localhost:8000/
from your browser. You should see “It worked!” message like this:


Now lets configure database connection for our application. Open the settings.py file. You will see the following lines:
view plain
copy to clipboard
print
?
  
DATABASE_ENGINE = ''   
DATABASE_NAME = ''   
DATABASE_USER = ''   
DATABASE_PASSWORD = ''  DATABASE_ENGINE = ''
DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
For our application we are using MySQL and the database name is “addressBook”. So we have to edit above lines as follows:
view plain
copy to clipboard
print
?
  
DATABASE_ENGINE = 'mysql'  
DATABASE_NAME = 'addressbook'  
DATABASE_USER = 'root'  
DATABASE_PASSWORD = 'password'  DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'addressbook'
DATABASE_USER = 'root'
DATABASE_PASSWORD = 'password'
Django’s models requires new application to be created. So type the following command to create new application:
view plain
copy to clipboard
print
?
  
$ python manage.py startapp addressbook  $ python manage.py startapp addressbook
This will create new directory called friends with the following contents:
__init.py__
models.py
views.py
Change directory to friends:
view plain
copy to clipboard
print
?
  
$ cd addressbook  $ cd addressbook
Edit models.py and write following contents in it:
view plain
copy to clipboard
print
?
  
from django.db import models   
class Contacts(models.Model):   
    name = models.CharField(max_length=30){ margin: 0.79in }   
    phone = models.CharField(max_length=30)   
    email = models.EmailField()  from django.db import models
class Contacts(models.Model):
    name = models.CharField(max_length=30){ margin: 0.79in }
    phone = models.CharField(max_length=30)
    email = models.EmailField()
The class Contacts will be a table in database and the variables ‘name’, ‘phone’ and ‘email’ will be the columns of Contacts table. Yeah.. no need of writing SQL queries, Django can do it for you. We will see that later.
Now we need to tell Django to use this ‘Contacts’ model(djangoapp/addressbook/models.py). Edit settings.py file, and goto INSTALLED_APPS section and add ‘addressbook’. It should look as follows:
view plain
copy to clipboard
print
?
  
INSTALLED_APPS = (   
    'django.contrib.auth',   
    'django.contrib.contenttypes',   
    'django.contrib.sessions',   
    'django.contrib.sites',   
    'addressbook',   
)  INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'addressbook',
)
Validating Models
view plain
copy to clipboard
print
?
  
$ python manage.py validate  $ python manage.py validate
The above command will validate models in your application. It will check for syntax and logical errors. If everything is ok then it should give 0 errors found message. And now run the following command to generate queries of the models:
view plain
copy to clipboard
print
?
  
$ python manage.py sqlall addressbook  $ python manage.py sqlall addressbook
In above command addressbook is the name of our app for which queries are to be generated. This wont create table in the database, it will just output the queries which will be executed at the time of creating tables. The table name will start with ‘addressbook_’ and ‘id’ column(Primary Key) is added by default. And now syncdb to create tables:
view plain
copy to clipboard
print
?
  
$ python manage.py syncdb  $ python manage.py syncdb
This will execute the statements which where generated by sqlall command. Now as we have our database ready, we will make use of Django’s Admin now. To use Admin we need to add ‘django.contrib.admin’ to INSTALLED_APPS:
view plain
copy to clipboard
print
?
  
INSTALLED_APPS = (   
    'django.contrib.auth',   
    'django.contrib.contenttypes',   
    'django.contrib.sessions',   
    'django.contrib.sites',   
    'addressbook',   
    'django.contrib.admin',   
)  INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'addressbook',
    'django.contrib.admin',
)
And now again sync the database:
view plain
copy to clipboard
print
?
  
$ python manage.py syncdb  $ python manage.py syncdb
As we have added admin in INSTALLED_APPS, syncdb will now ask you to create superuser for the application. We need superuser to access admin. Now we have to add our model to admin. To do that create a file called admin.py in our application(i.e. Under djangoapp/addressbook/):
view plain
copy to clipboard
print
?
  
from django.contrib import admin   
from djangoapp.addressbook.models import Contacts   
  
admin.site.register(Contacts)  from django.contrib import admin
from djangoapp.addressbook.models import Contacts
admin.site.register(Contacts)
And finally edit urls.py. Add (r’^admin/(.*)’, admin.site.root) in urlpatters so that we can access admin at
http://localhost:8000/admin
. Our urls.py file looks like this:
view plain
copy to clipboard
print
?
  
from django.conf.urls.defaults import *   
  
# Uncomment the next two lines to enable the admin:   
from django.contrib import admin   
admin.autodiscover()   
  
urlpatterns = patterns('',   
    # Uncomment the next line to enable the admin:   
    (r'^admin/(.*)', admin.site.root),   
)  from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:
    (r'^admin/(.*)', admin.site.root),
)
Now run the server:
view plain
copy to clipboard
print
?
  
$ python manage.py runserver  $ python manage.py runserver
You can access admin at
http://localhost:8000/admin
.

Click on Add link under Addressbook and start adding to the list. Django admin is very useful and it also provide every kinds of validations. Now we will write a view to display the added contacts. Open the file views.py under addressbook and write the following:  
view plain
copy to clipboard
print
?
  
from django.shortcuts import render_to_response   
from models import Contacts   
  
def contacts(request):   
    contacts_list = Contacts.objects.all()   
    return render_to_response('contacts_list.html', {'contacts_list': contacts_list})  from django.shortcuts import render_to_response
from models import Contacts
def contacts(request):
    contacts_list = Contacts.objects.all()
    return render_to_response('contacts_list.html', {'contacts_list': contacts_list})
In the above code we create a function called contacts. We retrieve all the records from Contacts model using Contacts.objects.all() . We use render_to_response to send variables to templates. The first argument is template name (contacts_list.html in our case) and second argument is a dictionary. The key in dictionary is the name of the variable that can be accessed in template contacts_list.html. The value in the dictionary is the variable that we will access in template. We have to create a directory called templates in addressbook and we will place contacts_list.html. In contacts_list.html we just loop through the contacts_list dictionary which we had passed in contacts function in views.py:
view plain
copy to clipboard
print
?
  
   
Address Book   
Address Book   
   
   
   
Name   
Phone   
Email   
   
{% for contact in contacts_list %}   
   
   
{{ contact.name }}   
   
{{ contact.phone }}   
   
{{ contact.email }}   
   
{% endfor %}   
   
  
Address Book
Address Book
Name
Phone
Email
{% for contact in contacts_list %}
{{ contact.name }}
{{ contact.phone }}
{{ contact.email }}
{% endfor %}
To see the output we have to map url to addressbook view. Change the urls.py so that it looks as follows:
view plain
copy to clipboard
print
?
  
from django.conf.urls.defaults import *   
from contacts.views import contacts   
# Uncomment the next two lines to enable the admin:   
from django.contrib import admin   
admin.autodiscover()   
  
urlpatterns = patterns('',   
    (r'^show/', contacts),   
    # Uncomment the next line to enable the admin:   
    (r'^admin/(.*)', admin.site.root),   
)  from django.conf.urls.defaults import *
from contacts.views import contacts
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
    (r'^show/', contacts),
    # Uncomment the next line to enable the admin:
    (r'^admin/(.*)', admin.site.root),
)
You can see the list of contacts at
http://localhost:8000/show/
.
In this post we covered some basics about Django like admin, creating a view and using templates. I will be posting more about Django soon.
References:
http://www.djangobook.com


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/78/showart_1891308.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP