1.安装:
(1)从Django官网下载安装包( Django-1.8.tar.gz当前最新):https://www.djangoproject.com/download/
(2)解压:tar -zxvf Django-1.8.tar.gz
(3)进入解压后目录后进行安装:cd Django-1.8 && sudo python setup.py install
(4)验证django是否安装成功:进入python,然后import django,看是否报错,不报错即安装成功
相关链接:http://daikeren.gitbooks.io/python-web-workshop/content/django_app/README.html
http://www.cnblogs.com/zhoujie/archive/2013/05/11/django1.html
http://djangobook.py3k.cn/2.0/chapter02/
2.初始工作:
(1)启动项目:django-admin.py startproject project-name
(2)编辑settings.py文件:修改时区,语言,数据库配置,installed_apps等
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', #新增
)
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3',
'ENGINE': 'django.db.backends.mysql',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME': 'xxx', #数据库名
'USER': 'xxxx', #数据库用户
'PASSWORD': 'xxxx', #数据库密码
'HOST': 'xxxx', #数据库机器
'PORT': '3306', #数据库端口
}
}
LANGUAGE_CODE = 'zh-cn'
TIME_ZONE = 'Asia/Shanghai'
(3)编辑urls.py:增加路由信息
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'first.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/index/$', 'blog.views.index'), #路径,视图处理函数
url(r'^blog/index1/$', 'blog.views.index1'),
#url(r'^blog/index/(d{2})/$', 'blog.views.index'),
)
(4)启动app:cd project-name && django-admin.py startapp app-name #app-name与settings.py中配置的要一致
(5)编辑views.py:编写视图处理方法(简单例子)
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,Context,Template
from django.shortcuts import render_to_response
from blog.models import Employee
# Create your views here.
'''
def index(req):
t = loader.get_template('index.html')
c = Context({})
return HttpResponse(t.render(c))
#return HttpResponse('<h1>hello welcome django</h1>')
'''
class person(object):
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
def say(self):
return "i'm "+self.name
def index(req):
t=loader.get_template('index.html')
c=Context({'name':'alen'})
res=t.render(c)
#emps=Employee.objects.all()
return HttpResponse(res)
def index1(req):
t=Template('<h1>hello {{name}} </h1>')
c=Context({'name':'alen'})
res=t.render(c)
return HttpResponse(res)
cat templates/index.html
<body>
<h1>hello {{name}}!</h1>
</body>
cat models.py
from django.db import models
# Create your models here.
class Employee(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
(6)启动server:python manage.py runserver ip:port,如果没有报错,在浏览器上就可以看到结果了
3.相关库:
(1)Cryptographic signing(cookie,session加解密)
简单使用实例
from django.core.signing import Signer #for cookie signer = Signer(salt='extra') sec_cookie = signer.sign('username') unsec_cookie = signer.unsign(sec_cookie)