VII django

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云原生数据库 PolarDB MySQL 版,通用型 2核4GB 50GB
简介:

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是围绕着RequestResponse进行处理,也就是无外乎“求”与“应”;

当请求一个页面时,django 把请求的metadata包装成一个HttpRequest对象(HttpRequest对象表示来自某客户端的一个单独的HTTP请求,HttpRequest对象是django自动创建的,它有很多属性),然后django加载合适的view方法,把这个HttpRequest对象作为第一个参数传给view方法,任何view方法都应该返回一个HttpResponse对象;

RequestResponse对象起到了服务器与客户机之间的信息传递作用,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() ,而不是手动加载模板、创建ContextHttpResponse对象,使用render_to_response则不再需要导入get_templateTemplateContextHttpResponse

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.pyurl 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.indexviewsmoduleindexmethod

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/

VII1101.jpg

 

 

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'},

        )

VII1102.jpg

 

 

3

模板变量使用:

 

普通变量:

dictionary

objectobject attributeobject 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

VII1103.jpg

 

 

4

模板运算符表达式(iffor):

{% if %}

{% else %}

{% endif %}

注:

andor不能全用;

ifelse中不能用()

可进行in运算;

例:

views.py   #render_to_response中返回HttpResponseuser去掉;

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>

VII1104.jpg

 

{% 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对象的引用,在嵌套循环的情况下用;

注:

Contextforloop变量:

在一个{% 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>

VII1105.jpg

 

 

5

urls.pyurl 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.pydef 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>

VII1106.jpg

 

例:

没有关键字参数,位置参数:

r'^blog/index/\d{2}/$'

views.pydef 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>

VII1107.jpg

 

 

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.htmlindex2.htmlindex3.htmlindex.html

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>{{ title }}</title>

</head>

<body>

        <h1>hello {{ name }}</h1>

</body>

</html>

VII1108.jpg

VII1109.jpg

VII1110.jpg

VII1111.jpg

 

]# 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

VII1112.jpg

 

 

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

VII1113.jpg

VII1114.jpg

Blog-->Users-->Add userName:jowinSex:male-->Save and add another

Name:carlySex:female-->Save

VII1115.jpg

VII1116.jpg

 

]# 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后再查询

VII1117.jpg

sqlite> SELECT * FROM blog_user;

1|jowin|m

 

Auth-->Users-->Add user

VII1118.jpg

Personal Info

Permissions-->Active有效,Staff status该用户是否登录到管理界面-->Save

VII1119.jpg

VII1120.jpg

 

 

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

VII1121.jpg

VII1122.jpg

In [92]: books[0].authors.add(authors[0])

In [93]: books[0].authors.all()

Out[93]: [<Author: jowin>, <Author: chai>]

VII1123.jpg

 

 

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

VII1124.jpg

VII1125.jpg

VII1126.jpg

 

 

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

VII1127.jpg

VII1128.jpg

 

views.py文件中定义后台打印:

            print uf.cleaned_data['username']

            print uf.cleaned_data['headimg'].name

            print uf.cleaned_data['headimg'].size

VII1129.jpg

 

views.py文件中定义后台打印:

            print uf.cleaned_data['username']

            print req.FILES

VII1130.jpg

 

]# 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

VII1131.jpg

VII1132.jpg

]# 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,如需转载请自行联系原作者

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
2月前
|
SQL API 数据库
为什么聪明人都选择Django/Flask?看完这篇,你也会有答案!
无论是选择Django还是Flask,你都能享受到它们带来的便利与高效。Django以其全面的功能和高效的开发体验,成为了快速搭建大型Web应用的优选;而Flask则以其轻量级和灵活性,成为了快速原型开发和定制化项目的理想选择。无论你处于Web开发的哪个阶段,Django和Flask都能成为你强大的助力。现在,你已经有了选择它们的答案,接下来,就是开启你的Web开发之旅了!
45 2
|
7月前
|
调度 Apache 数据库
Django 学习教程-第一个 Django 应用
本章主要讲述了如何创建一个Django项目,以一个投票案例程序介绍了Django的请求和响应流程。
95 1
|
SQL 安全 数据库
【Django入门】第一个Django项目
【Django入门】第一个Django项目
87 0
【Django入门】第一个Django项目
|
SQL 缓存 Shell
Django系列:Django开发环境配置与第一个Django项目
Django开发环境配置与第一个Django项目的搭建。包括虚拟隔离环境,命令行工具的使用等。
164 0
|
数据安全/隐私保护 Python Windows
ycharm+Django之Django学习(1)(初学者)
教学属于博主的自学记录,适合刚学习Django的同学,如果比较熟的就不用look了!!!
132 0
ycharm+Django之Django学习(1)(初学者)
|
存储 SQL 前端开发
Django入门:第八章、模板引擎设置
Django入门:第八章、模板引擎设置
149 0
Django入门:第八章、模板引擎设置
|
前端开发 JavaScript Python
Django入门:第十章、静态文件设置
Django入门:第十章、静态文件设置
234 0
Django入门:第十章、静态文件设置
|
Python 开发工具
|
Python
django 1.8 官方文档翻译:7-3 Django管理文档生成器
Django管理文档生成器 Django的admindocs应用从模型、视图、模板标签以及模板过滤器中,为任何INSTALLED_APPS中的应用获取文档。
898 0
|
测试技术 Python 开发者
django 1.8 官方文档翻译:6-5-1 Django中的测试
Django中的测试 自动化测试对于现代web开发者来说,是非常实用的除错工具。你可以使用一系列测试– 测试套件 – 来解决或者避免大量问题: 当你编写新代码的时候,你可以使用测试来验证你的代码是否像预期一样工作。
926 0

热门文章

最新文章