Django is available open-source under the BSD license. We recommend using the latest version of Python 3. The last version to support Python 2.7 is Django 1.11 LTS.
Django特点:
强大的数据库功能(拥有强大的数据库操作接口(QuerySet API),如需要也能执行原生SQL);
自带强大后台(几行简单的代码就让网站拥有一个强大的后台,轻松管理内容);
优雅的网址(用正则匹配网址,传递到对应函数,随意定义,如你所想);
模板系统(强大,易扩展的模板系统,设计简易,代码,样式分开设计,更容易管理);
前后端分离时,也可以用Django开发API,完全不用模板系统;
缓存系统(与Memcached, Redis等缓存系统联用,更出色的表现,更快的加载速度);
国际化(完全支持多语言应用,允许你定义翻译的字符,轻松翻译成不同国家的语言);
https://www.djangoproject.com/download/2.0/tarball/
https://www.djangoproject.com/download/1.3.3/tarball/
django.http.HttpResponse
django是围绕着Request与Response进行处理,也就是无外乎“求”与“应”;
当请求一个页面时,django 把请求的metadata包装成一个HttpRequest对象(HttpRequest对象表示来自某客户端的一个单独的HTTP请求,HttpRequest对象是django自动创建的,它有很多属性),然后django加载合适的view方法,把这个HttpRequest对象作为第一个参数传给view方法,任何view方法都应该返回一个HttpResponse对象;
Request和Response对象起到了服务器与客户机之间的信息传递作用,Request 对象用于接收客户端浏览器提交的数据,而Response对象的功能则是将服务器端的数据发送到客户端浏览器,比如在view层,一般都是以下列代码结束一个def,
return HttpResponse(html)
或
return render_to_response('nowamagic.html', {'data': data})
django.shortcuts.render_to_response
由于加载模板、填充context、将经解析的模板结果返回为HttpResponse对象,这一系列操作实在太常用了,Django 提供了一条仅用一行代码就完成所有这些工作的捷径,即位于 django.shortcuts模块中的render_to_response()函数,大多数时候使用render_to_response() ,而不是手动加载模板、创建Context和HttpResponse对象,使用render_to_response则不再需要导入get_template、Template、Context和HttpResponse;
render_to_response()的第一个参数必须是要使用的模板名称,如果要给定第二个参数,那么该参数必须是为该模板创建Context 时所使用的字典,如果不提供第二个参数,render_to_response()使用一个空字典;
render_to_response()返回 HttpResponse对象,因此仅需在视图中return该值;
例:
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})
1、
安装:
]# tar xf Django-1.3.3.tar.gz
]# cd Django-1.3.3
]# python2.7 setup.py install
]# ipython
In [1]: import django #验证是否安装成功
]# vim /etc/profile.d/python27.sh
export PATH=$PATH:/ane/python2.7/bin
]# ll -h /ane/python2.7/bin/django-admin.py
-rwxr-xr-x 1 root root 127 Dec 6 16:56 /ane/python2.7/bin/django-admin.py
]# ipython manage.py shell #进入django调试模式;
]# django-admin.py startproject web01 #创建项目
]# ls web01/ #有__init__.py文件说明web01目录为包,manage.py管理工具,settings.py当前工程的配置,urls.py是url config文件;
__init__.py manage.py settings.py urls.py
]# vim web01/settings.py
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
……
}
#TIME_ZONE = 'America/Chicago'
TIME_ZONE = 'Asia/Shanghai'
#LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-cn'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
)
]# vim web01/urls.py #blog.views.index,views为module,index为method;
urlpatterns = patterns('',
url(r'^blog/index/$','blog.views.index'),
)
]# cd web01/
]# django-admin.py startapp blog
]# ls blog/ #models.py模型文件,views.py视图文件,tests.py仅测试无意义;
__init__.py models.py tests.py views.py
]# vim blog/views.py
#!/usr/bin/env python2.7
# Create your views here.
from django.http import HttpResponse
def index(req):
return HttpResponse('<h1>hello world</h1>')
[root@tmsapp web01]# pwd
/ane/PycharmProjects/web01
]# python2.7 manage.py runserver
Validating models...
0 errors found
Django version 1.3.3, using settings 'web01.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[07/Dec/2017 10:23:26] "GET / HTTP/1.1" 404 1986
[07/Dec/2017 10:24:04] "GET /blog/index HTTP/1.1" 301 0
[07/Dec/2017 10:24:04] "GET /blog/index/ HTTP/1.1" 200 20
访问http://127.0.0.1:8000/blog/index/
2、
模板文件导入:
]# pwd
/ane/PycharmProjects/web01
]# mkdir blog/templates #将网站静态文件放至此处,容易管理;
]# vim blog/templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ title }}</title>
</head>
<body>
<h1>hello {{ user }}</h1>
</body>
</html>
]# vim blog/views.py
#!/usr/bin/env python2.7
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(req):
#return HttpResponse('<h1>hello world</h1>')
return render_to_response(
'index.html',
{'title':'my page','user':'tom'},
)
3、
模板变量使用:
普通变量:
dictionary;
object(object attribute,object method),对象方法在html中不用写参数;
list;
变量优先级:dictionary,object attribute,object method,list;
例:
]# vim blog/views.py
#!/usr/bin/env python2.7
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
class Person(object):
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def say(self):
return 'I am %s' % self.name
def index(req):
#user = {'name':'tom','age':18,'sex':'male'}
user = Person('jowin',18,'male')
book_list = ['python','java','php','ruby','objectc','js']
#return HttpResponse('<h1>hello world</h1>')
return render_to_response(
'index.html',
{'title':'my page','user':user,'book_list':book_list}
)
]# vim blog/templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ title }}</title>
</head>
<body>
<h1>hello {{ user.name }}</h1>
<li>age: {{ user.age }}</li>
<li>sex: {{ user.sex }}</li>
<li>{{ book_list.0 }}</li>
<li>{{ book_list.1 }}</li>
<li>{{ book_list.2 }}</li>
<li>{{ book_list.3 }}</li>
<li>{{ book_list.4 }}</li>
<div>
the {{ user.name }} say: {{ user.say }}
</div>
</body>
</html>
]# python2.7 manage.py runserver
4、
模板运算符表达式(if;for):
{% if %}
…
{% else %}
…
{% endif %}
注:
and和or不能全用;
if、else中不能用();
可进行in运算;
例:
views.py: #render_to_response中返回HttpResponse的user去掉;
from django.http import HttpResponse
from django.shortcuts import render_to_response
class Person(object):
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def say(self):
return 'I am %s' % self.name
def index(req):
#user = {'name':'tom','age':18,'sex':'male'}
user = Person('jowin',18,'male')
book_list = ['python','java','php','ruby','objectc','js']
#return HttpResponse('<h1>hello world</h1>')
return render_to_response(
'index.html',
{'title':'my page','book_list':book_list}
)
templates/index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ title }}</title>
</head>
<body>
{% if user %}
<li>name: {{ user.name }}</li>
{% else %}
the user is not exists
{% endif %}
</body>
</html>
{% for %}
…
{% empty %} #empty段为可选;
…
{% endfor %}
django forloop模板变量:
forloop变量仅仅能够在循环中使用,在模板解析器碰到{% endfor %}标签后,forloop就不可访问了;
forloop.counter #总是一个表示当前循环的执行次数的整数计数器,这个计数器是从1开始的,所以在第一次循环时forloop.counter将会被设置为1;
forloop.counter0 #类似于 forloop.counter,但是它是从0计数的。,第一次执行循环时这个变量会被设置为0;
forloop.revcounter #表示循环中剩余项的整型变量,在循环初次执行时forloop.revcounter 将被设置为序列中项的总数,最后一次循环执行中,这个变量将被置1;
forloop.reccounter0 #类似于forloop.revcounter,但它以0做为结束索引,在第一次执行循环时,该变量会被置为序列的项的个数减1;
forloop.first #是一个布尔值,如果该迭代是第一次执行,那么它被置为True;
forloop.last #是一个布尔值,在最后一次执行循环时被置为True,常用于在一系列的链接之间放置管道符和为列表的每个单词的加上逗号,如
{% for link in links %}
{{ link }}
{% if not forloop.last %}
|
{% endif %}
{% endfor %}
该模板会产生如下的结果:Link1 | Link2 | Link3 | Link4;
forloop.parentloop #是一个指向当前循环的上一级循环的forloop对象的引用,在嵌套循环的情况下用;
注:
Context和forloop变量:
在一个{% for %}块中,已存在的变量会被移除,以避免forloop变量被覆,django会把这个变量移动到forloop.parentloop中,通常我们不用担心这个问题,但是一旦我们在模板中定义了forloop这个变量(当然我们反对这样做),在{% for %}块中它会在forloop.parentloop被重新命名;
例:
views.py:
#!/usr/bin/env python2.7
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(req):
user = {'name':'tom','age':18,'sex':'male'}
#user = Person('jowin',18,'male')
book_list = ['python','java','php','ruby','objectc','js']
#return HttpResponse('<h1>hello world</h1>')
return render_to_response(
'index.html',
{'title':'my page','book_list':book_list,'user':user}
)
templates/index.html:
<body>
{% for book in book_list %}
<li>{{ book }}</li>
{% endfor %}
{% for k in user %} #仅循环字典中的key
<li>{{ k }}</li>
{% endfor %}
{% for k,v in user.items %}
<li>{{ forloop.counter }}.{{ k }}:{{ v }}</li>
{% endfor %}
</body>
5、
urls.py,url config的几种方式:
一)
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^blog/index/$','blog.views.index'), #此处'blog.views.index'是字符串形式
)
二)
from django.conf.urls.defaults import patterns, include, url
from blog.views import index
urlpatterns = patterns('',
url(r'^blog/index/$',index), #此处index不是字符串形式,而是引用变量的形式
)
三)
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('blog.views',
url(r'^blog/index/$','index'), #字符串形式
)
例:
把url中的一部分作为参数传递,关键字参数id:
r'^blog/index/(?P<id>\d{2})/$'
views.py中def index(req,id):
]# vim urls.py
url(r'^blog/index/(?P<id>\d{2})/$','blog.views.index'),
]# vim blog/views.py
def index(req,id):
user = {'name':'tom','age':18,'sex':'male'}
#user = Person('jowin',18,'male')
book_list = ['python','java','php','ruby','objectc','js']
#return HttpResponse('<h1>hello world</h1>')
return render_to_response(
'index.html',
{'title':'my page','book_list':book_list,'user':user,'id':id}
)
]# vim blog/templates/index.html
<body>
id: {{ id }}
</body>
例:
没有关键字参数,位置参数:
r'^blog/index/\d{2}/$'
views.py中def index(req):
]# vim urls.py
url(r'^blog/index/\d{2}/$','blog.views.index'),
]# vim blog/views.py
def index(req):
user = {'name':'tom','age':18,'sex':'male'}
#user = Person('jowin',18,'male')
book_list = ['python','java','php','ruby','objectc','js']
#return HttpResponse('<h1>hello world</h1>')
return render_to_response(
'index.html',
{'title':'my page','user':user,'book_list':book_list}
)
]# vim blog/templates/index.html
<body>
{% if user %}
<li>name: {{ user.name }}</li>
{% else %}
the user is not exists
{% endif %}
{% for book in book_list %}
<li>{{ book }}</li>
{% endfor %}
{% for k in user %}
<li>{{ k }}</li>
{% endfor %}
{% for k,v in user.items %}
<li>{{ forloop.counter }}.{{ k }}:{{ v }}</li>
{% endfor %}
</body>
6、
模板的使用:
django.shortcuts.render_to_response('index.html',{'name':'jowin'})(index.html为模板文件,{'name':'jowin'}为需要渲染的数据)这一步相当于使用标准模板的三步;
t = loader.get_template('index.html') #加载模板
c = Context({'name':'jowin'}) #生成context对象
return HttResponse(t.render(c)) #渲染输出
]# django-admin.py startproject web02
]# cd web02/
]# django-admin.py startapp blog
]# vim settings.py
INSTALLED_APPS = (
'blog',
)
]# vim urls.py
url(r'^index/$','blog.views.index'),
url(r'^index1/$','blog.views.index1'),
url(r'^index2/$','blog.views.index2'),
url(r'^index3/$','blog.views.index3'),
]# cd blog/
]# mkdir templates/
]# vim views.py
#!/usr/bin/env python2.7
#
from django.template import loader,Context,Template
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(req):
t = loader.get_template('index.html') #加载模板
c = Context({'title':'my-site','name': 'carly'}) #生成context对象
html = t.render(c) #渲染输出
return HttpResponse(html)
def index1(req):
t = loader.get_template('index1.html')
c = Context({'title':'my-site1','name':'jowin'})
return HttpResponse(t.render(c))
def index2(req):
return render_to_response('index2.html',{'title':'my-site2','name':'chai'})
def index3(req):
t = Template('<h1>hello {{ name }}</h1>')
c = Context({'name':'jowin'})
return HttpResponse(t.render(c))
]# vim templates/index.html #index1.html和index2.html和index3.html同index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ title }}</title>
</head>
<body>
<h1>hello {{ name }}</h1>
</body>
</html>
]# cd ../
]# ipython manage.py shell
In [1]: from django.template import loader,Context
In [2]: from django.http import HttpResponse
In [3]: t = loader.get_template('index.html')
In [4]: t
Out[4]: <django.template.base.Template at 0x2cd2d90>
In [5]: c = Context({'title':'my-site','name':'carly'})
In [6]: c
Out[6]: [{'name': 'carly', 'title': 'my-site'}]
In [7]: html = t.render(c)
In [8]: html
Out[8]: u'<!DOCTYPE html>\n<html>\n<head>\n<meta charset="utf-8" />\n<title>my-site</title>\n</head>\n<body>\n\t<h1>hello carly</h1>\n</body>\n</html>'
In [9]: from django.shortcuts import render_to_response
In [10]: render_to_response('index.html',{'title':'my-site','name':'carly'})
Out[10]: <django.http.HttpResponse at 0x2ce06d0>
7、
DB使用:
]# yum -y install MySQL-python
]# rpm -qa MySQL-python
MySQL-python-1.2.3-0.3.c1.1.el6.x86_64
]# ipython
In [1]: import MySQLdb
]# /etc/init.d/mysqld start
Starting mysqld: [ OK ]
]# mysql -uroot
mysql> CREATE DATABASE web02 DEFAULT CHARSET=UTF8;
Query OK, 1 row affected (0.00 sec)
]# pwd
/ane/PycharmProjects/web02
]# vim settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'web02', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'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.
}
}
INSTALLED_APPS = (
'blog',
)
]# vim blog/models.py
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=20)
]# python2.7 manage.py syncdb #同步动作,此步会自动检查INSTALLED_APPS,进而自动创建表;
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table blog_employee
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'root'): root
E-mail address: jowin@163.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
No fixtures found.
mysql> use web02;
mysql> use web02;
Database changed
mysql> SELECT * FROM blog_employee;
Empty set (0.00 sec)
mysql> DESC blog_employee; #默认加了id字段;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)
8、
插入数据三种方式:
方式一:
]# ipython manage.py shell
In [1]: from blog.models import Employee;
In [2]: Employee
Out[2]: blog.models.Employee
In [3]: emp = Employee() #先实例化
In [4]: emp.name = 'jowin' #通过实例修改字段属性
In [5]: emp.save()
mysql> select * from blog_employee;
+----+-------+
| id | name |
+----+-------+
| 1 | jowin |
+----+-------+
1 row in set (0.00 sec)
方式二:
In [6]: emp = Employee(name='chai') #在创建实例时,用构造方法添加字段属性
In [7]: emp.save()
mysql> select * from blog_employee;
+----+-------+
| id | name |
+----+-------+
| 1 | jowin |
| 2 | chai |
+----+-------+
2 rows in set (0.00 sec)
方式三:
In [8]: emp = Employee.objects.create(name='carly') #通过管理器调用create方法
mysql> select * from blog_employee;
+----+-------+
| id | name |
+----+-------+
| 1 | jowin |
| 2 | chai |
| 3 | carly |
+----+-------+
3 rows in set (0.00 sec)
In [9]: emp
Out[9]: <Employee: Employee object>
In [10]: emps = Employee.objects.all()
In [11]: emps #三条记录看不出具体信息,可通过在modes.py中定义def __unicode__(self)解决
Out[11]: [<Employee: Employee object>, <Employee: Employee object>, <Employee: Employee object>]
]# vim blog/models.py
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=20)
def __unicode__(self):
return self.name
]# ipython manage.py shell
In [1]: from blog.models import Employee
In [2]: emps = Employee.objects.all()
In [3]: emps #有具体name的记录
Out[3]: [<Employee: jowin>, <Employee: chai>, <Employee: carly>]
]# vim urls.py
url(r'^index/$','blog.views.index'),
]# vim blog/views.py
from django.shortcuts import render_to_response
from blog.modes import Employee
def index(req):
emps = Employee.objects.all()
return render_to_response('index.html',{'emps':emps})
]# vim blog/templates/index.html
<body>
<!--{{ emps }}-->
{% for emp in emps %}
<div>{{ forloop.counter }} {{ emp }}</div>
{% endfor %}
</body>
]# python2.7 manage.py runserver
9、
many 2 one:
]# pwd
/ane/PycharmProjects/web02
]# vim blog/models.py
from django.db import models
class Entry(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Blog(models.Model):
name = models.CharField(max_length=30)
entry = models.ForeignKey(Entry)
def __unicode__(self):
return self.name
]# python2.7 manage.py syncdb
]# ipython manage.py shell
In [1]: from blog.models import Entry,Blog
In [2]: entry1 = Entry.objects.create(name='jowin') #先创建one再创建many
In [3]: entry2 = Entry.objects.create(name='chai')
In [4]: entry3 = Entry.objects.create(name='carly')
In [6]: entry1
Out[6]: <Entry: jowin>
In [8]: blog1 = Blog.objects.create(name='jowin_blog1',entry=entry1) #创建many
In [9]: blog1
Out[9]: <Blog: jowin_blog1>
In [10]: blog1.entry #在many端查找
Out[10]: <Entry: jowin>
In [11]: blog1.entry_id
Out[11]: 1L
In [12]: entry1.blog_set.all() #在one端查找
Out[12]: [<Blog: jowin_blog1>]
10、
用admin后台管理db:
]# pwd
/ane/PycharmProjects
]# django-admin.py startproject web04
]# cd web04/
]# django-admin.py startapp blog
]# vim settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'web04.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'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.
}
}
INSTALLED_APPS = (
……
'blog',
'django.contrib.admin',
)
]# vim urls.py
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
]# vim blog/models.py
from django.db import models
sex_choices = (('f','famale'),('m','male'))
class User(models.Model):
name = models.CharField(max_length=30)
sex = models.CharField(max_length=1,choices=sex_choices)
def __unicode__(self):
return self.name
]# vim blog/admin.py
from django.contrib import admin
from blog.models import User
admin.site.register(User)
]# python2.7 manage.py syncdb
Creating table blog_user
Creating table django_admin_log #后台管理表
]# python2.7 manage.py runserver
Blog-->Users-->Add user,Name:jowin,Sex:male-->Save and add another
Name:carly,Sex:female-->Save
]# pwd
/ane/PycharmProjects/web04
]# ls
blog __init__.py __init__.pyc manage.py settings.py settings.pyc urls.py urls.pyc web04.db
]# sqlite3 web04.db
SQLite version 3.6.20
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .help
sqlite> .tables
auth_group auth_user_user_permissions
auth_group_permissions blog_user
auth_message django_admin_log
auth_permission django_content_type
auth_user django_session
auth_user_groups django_site
sqlite> SELECT * FROM blog_user;
1|jowin|m
2|carly|f
在admin页面删除用户carly后再查询
sqlite> SELECT * FROM blog_user;
1|jowin|m
Auth-->Users-->Add user
Personal Info
Permissions-->Active有效,Staff status该用户是否登录到管理界面-->Save
11、
many 2 many:
]# vim blog/models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=30)
authors = models.ManyToManyField(Author)
def __unicode__(self):
return self.name
]# python2.7 manage.py syncdb
Creating table blog_author
Creating table blog_book_authors
Creating table blog_book
]# sqlite3 web05.db
sqlite> .tables
auth_group blog_author
auth_group_permissions blog_book
auth_message blog_book_authors
auth_permission django_content_type
auth_user django_session
auth_user_groups django_site
auth_user_user_permissions
]# ipython manage.py shell
In [1]: from blog.models import Author,Book
In [2]: Author.objects.create(name='jowin') #或使用author1 = Author();author1.name = 'jowin';author1.save()
Out[2]: <Author: jowin>
In [3]: Author.objects.create(name='chai')
Out[3]: <Author: chai>
In [4]: Author.objects.create(name='carly')
Out[4]: <Author: carly>
In [5]: Author.objects.create(name='david')
Out[5]: <Author: david>
In [6]: authors = Author.objects.all()
In [7]: authors
Out[7]: [<Author: jowin>, <Author: chai>, <Author: carly>, <Author: david>]
In [8]: b1 = Book.objects.create(name='python book1')
In [9]: b1
Out[9]: <Book: python book1>
In [10]: jowin = Author.objects.get(name__exact='jowin')
In [12]: b1.authors.add(jowin) #一本书添加多个作者
In [18]: b1.authors.add(authors[1])
In [20]: b1.authors.remove(authors[0])
In [21]: b1.authors.all()
Out[21]: [<Author: chai>]
In [22]: b1.authors.add(authors[3])
In [23]: b1.authors.all()
Out[23]: [<Author: chai>, <Author: david>]
In [24]: b1.authors.filter(name__exact='david')
Out[24]: [<Author: david>]
In [25]: authors[3].book_set.all() #获取一个作者对应的所有书
Out[25]: [<Book: python book1>]
In [26]: authors[3].book_set.create(name='python book2') #给一作者添加书籍
Out[26]: <Book: python book2>
In [27]: authors[3].book_set.all() #一个作者对应的所有书
Out[27]: [<Book: python book1>, <Book: python book2>]
In [28]: books = Book.objects.all()
In [29]: books
Out[29]: [<Book: python book1>, <Book: python book2>]
In [30]: david = authors[3]
In [31]: david.book_set.remove(books[0]) #删除一个作者对应的某一本书
In [33]: david.book_set.all() #获取一个作者对应的所有书
Out[33]: [<Book: python book2>]
In [34]: for author in Author.objects.all():
....: for book in author.book_set.all():
....: print book
....:
python book1
python book2
In [53]: b3 = Book.objects.create(name='web book')
In [64]: jowin = Author.objects.get(name__exact='jowin')
In [65]: b3.authors.add(jowin)
In [66]: b3
Out[66]: <Book: web book>
In [67]: b3.authors.all()
Out[67]: [<Author: jowin>]
In [68]: authors[0].book_set.all()
Out[68]: [<Book: web book>]
]# vim urls.py
urlpatterns = patterns('',
……
url(r'^blog/show_author/$','blog.views.show_author'),
url(r'^blog/show_book/$','blog.views.show_book'),
)
]# vim blog/views.py
from blog.models import Author
from blog.models import Book
from django.shortcuts import render_to_response
def show_author(req):
authors = Author.objects.all()
return render_to_response('show_author.html',{'authors':authors})
def show_book(req):
books = Book.objects.all()
return render_to_response('show_book.html',{'books':books})
]# vim blog/templates/show_author.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
{% for author in authors %}
<li>{{ author }}</li>
{% endfor %}
</body>
</html>
]# vim blog/templates/show_book.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
{% for book in books %}
<h1>{{ book.name }}</h1>
<div>
{% for author in book.authors.all %} #此处all后不用加(),否则语法错误
<li>{{ author }}</li>
{% endfor %}
</div>
{% endfor %}
</body>
</html>
]# python2.7 manage.py runserver
In [92]: books[0].authors.add(authors[0])
In [93]: books[0].authors.all()
Out[93]: [<Author: jowin>, <Author: chai>]
12、
form表单:
]# django-admin.py startproject web06
]# cd web06
]# django-admin.py startapp blog
]# vim settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
INSTALLED_APPS = (
……
'blog',
)
]# vim urls.py
url(r'^blog/register/$,'blog.views.register'),
]# vim blog/views.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
class UserForm(forms.Form):
name = forms.CharField()
def register(req):
if req.method == 'POST':
form = UserForm(req.POST)
if form.is_valid():
print form.cleaned_data
return HttpResponse('ok')
else:
form = UserForm()
return render_to_response('register.html',{'form':form})
]# mkdir blog/templates
]# vim blog/templates/register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form method='post'>
{{ form }}
<input type='submit' value='ok'/>
</form>
</body>
</html>
]# python2.7 manage.py runserver
13、
文件上传(方式一):
上传文件完成绑定动作,需两步:
uf = UserForm(req.POST,req.FILES) #views.py
<form method='post' enctype='multipart/form-data'> #register.html
]# django-admin.py startproject web07
]# cd !$
]# django-admin.py startapp blog
]# vim settings.py
]# vim urls.py
]# vim blog/views.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
class UserForm(forms.Form):
username = forms.CharField()
headimg = forms.FileField()
def register(req):
if req.method == 'POST':
# uf = UserForm(req.POST)
uf = UserForm(req.POST,req.FILES)
if uf.is_valid():
print uf.cleaned_data['username']
# print req.FILES
print uf.cleaned_data['headimg'].name
print uf.cleaned_data['headimg'].size
fp = file('./blog/upload/' + uf.cleaned_data['headimg'].name,'wb')
s = uf.cleaned_data['headimg'].read()
fp.write(s)
fp.close()
return HttpResponse('ok')
else:
uf = UserForm()
return render_to_response('register.html',{'uf':uf})
]# mkdir blog/upload
]# mkdir blog/templates
]# vim blog/templates/register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>\u7528\u6237\u6ce8\u518c</div>
<div>
<form method='post' enctype='multipart/form-data'>
{{ uf.as_p }}
<input type='submit' value='confirm'/>
</form>
</div>
</body>
</html>
]# python2.7 manage.py runserver
views.py文件中定义后台打印:
print uf.cleaned_data['username']
print uf.cleaned_data['headimg'].name
print uf.cleaned_data['headimg'].size
views.py文件中定义后台打印:
print uf.cleaned_data['username']
print req.FILES
]# ll -h blog/upload/
total 1.8M
-rw-r--r-- 1 root root 1.2M Dec 14 10:57 pip-9.0.1.tar.gz
-rw-r--r-- 1 root root 623K Dec 14 10:58 setuptools-19.6.1.tar.gz
14、
文件上传方式二(后台管理+DB):
上传文件后完整的路径为:MEDIA_ROOT(setting.py) + upload_to(models.py)
]# django-admin.py startproject web08
[root@tmsapp PycharmProjects]# cd !$
cd web08
[root@tmsapp web08]# django-admin.py startapp blog
]# vim settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'web08.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'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.
}
}
MEDIA_ROOT = '/headImg'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'django.contrib.admin',
)
]# vim blog/models.py
from django.db import models
class User(models.Model):
username = models.CharField(max_length=30)
headimg = models.FileField(upload_to='./upload/')
def __unicode__(self):
return self.username
]# vim urls.py
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/register/$','blog.views.register'),
)
]# vim blog/views.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render_to_response
class UserForm(forms.Form):
username = forms.CharField()
headimg = forms.FileField()
def register(req):
if req.method == 'POST':
# uf = UserForm(req.POST)
uf = UserForm(req.POST,req.FILES)
if uf.is_valid():
print uf.cleaned_data['username']
# print req.FILES
print uf.cleaned_data['headimg'].name
print uf.cleaned_data['headimg'].size
fp = file('./blog/upload/' + uf.cleaned_data['headimg'].name,'wb')
s = uf.cleaned_data['headimg'].read()
fp.write(s)
fp.close()
return HttpResponse('ok')
else:
uf = UserForm()
return render_to_response('register.html',{'uf':uf})
]# vim blog/admin.py
from django.contrib import admin
from django.models import User
admin.site.register(User)
]# python2.7 manage.py syncdb
Creating table blog_user
Creating table django_admin_log
]# sqlite3 web08.db
sqlite> .tables
auth_group auth_user_user_permissions
auth_group_permissions blog_user
auth_message django_admin_log
auth_permission django_content_type
auth_user django_session
auth_user_groups django_site
sqlite> .exit
]# python2.7 manage.py runserver
Blog-->Users-->Add user,Username:jowin,Browser:在本地选择文件-->Save
]# ll -h /headImg/upload/ #/headImg会自动创建
total 1.2M
-rwxr-xr-x 1 root root 1.2M Dec 14 11:45 pip-9.0.1.tar.gz
本文转自 chaijowin 51CTO博客,原文链接:http://blog.51cto.com/jowin/2050655,如需转载请自行联系原作者