天天看點

VII django

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

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

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

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

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

    )

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

]# python2.7 manage.py runserver

4、

模闆運算符表達式(if;for):

{% if %}

{% else %}

{% endif %}

注:

and和or不能全用;

if、else中不能用();

可進行in運算;

views.py:   #render_to_response中傳回HttpResponse的user去掉;

        self.name = name

        {'title':'my page','book_list':book_list}

templates/index.html:

        {% if user %}

            <li>name: {{ user.name }}</li>

        {% else %}

            the user is not exists

        {% endif %}

{% 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 %}

該模闆會産生如下的結果:Link1 | Link2 | Link3 | Link4;

forloop.parentloop   #是一個指向目前循環的上一級循環的forloop對象的引用,在嵌套循環的情況下用;

Context和forloop變量:

在一個{% for %}塊中,已存在的變量會被移除,以避免forloop變量被覆,django會把這個變量移動到forloop.parentloop中,通常我們不用擔心這個問題,但是一旦我們在模闆中定義了forloop這個變量(當然我們反對這樣做),在{% for %}塊中它會在forloop.parentloop被重新命名;

views.py:

    user = {'name':'tom','age':18,'sex':'male'}

    #user = Person('jowin',18,'male')

        {'title':'my page','book_list':book_list,'user':user}

        {% for book in book_list %}

            <li>{{ book }}</li>

        {% endfor %}

        {% for k in user %}   #僅循環字典中的key

            <li>{{ k }}</li>

        {% for k,v in user.items %}

            <li>{{ forloop.counter }}.{{ k }}:{{ v }}</li>

         </body>

5、

urls.py,url config的幾種方式:

一)

from django.conf.urls.defaults import patterns, include, url

    url(r'^blog/index/$','blog.views.index'),   #此處'blog.views.index'是字元串形式

二)

from blog.views import index

    url(r'^blog/index/$',index),   #此處index不是字元串形式,而是引用變量的形式

三)

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

def index(req,id):

        {'title':'my page','book_list':book_list,'user':user,'id':id}

         <body>

        id: {{ id }}

沒有關鍵字參數,位置參數:

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

views.py中def index(req):

    url(r'^blog/index/\d{2}/$','blog.views.index'),

        {% for k in user %}

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

    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

#

from django.template import loader,Context,Template

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

]# vim templates/index.html   #index1.html和index2.html和index3.html同index.html

<head>

<meta charset="utf-8" />

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

</head>

<body>

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

</body>

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

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)

/ane/PycharmProjects/web02

    '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.

    }

]# 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: [email protected]

Password:

Password (again):

Superuser created successfully.

Installing custom SQL ...

Installing indexes ...

No fixtures found.

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、

插入資料三種方式:

方式一:

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()

|  2 | chai  |

方式三:

In [8]: emp = Employee.objects.create(name='carly')   #通過管理器調用create方法

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

    def __unicode__(self):

        return self.name

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

from blog.modes import Employee

    emps = Employee.objects.all()

    return render_to_response('index.html',{'emps':emps})

         <!--{{ emps }}-->

         {% for emp in emps %}

         <div>{{ forloop.counter }} {{ emp }}</div>

         {% endfor %}

9、

many 2 one:

class Entry(models.Model):

    name = models.CharField(max_length=30)

class Blog(models.Model):

    entry = models.ForeignKey(Entry)

]# python2.7 manage.py syncdb

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:

/ane/PycharmProjects

]# django-admin.py startproject web04

]# cd web04/

        '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.

         ……

    'django.contrib.admin',

from django.contrib import admin

admin.autodiscover()

    url(r'^admin/', include(admin.site.urls)),

sex_choices = (('f','famale'),('m','male'))

class User(models.Model):

    sex = models.CharField(max_length=1,choices=sex_choices)

]# vim blog/admin.py

from blog.models import User

admin.site.register(User)

Creating table blog_user

Creating table django_admin_log   #背景管理表

Blog-->Users-->Add user,Name:jowin,Sex:male-->Save and add another

Name:carly,Sex:female-->Save

/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;

Auth-->Users-->Add user

Personal Info

Permissions-->Active有效,Staff status該使用者是否登入到管理界面-->Save

11、

many 2 many:

class Author(models.Model):

class Book(models.Model):

    authors = models.ManyToManyField(Author)

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_user                   django_session           

auth_user_groups            django_site              

auth_user_user_permissions

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

    url(r'^blog/show_author/$','blog.views.show_author'),

    url(r'^blog/show_book/$','blog.views.show_book'),

from blog.models import Author

from blog.models import Book

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

<title></title>

  {% for author in authors %}

  <li>{{ author }}</li>

  {% endfor %}

]# vim blog/templates/show_book.html

         {% for book in books %}

         <h1>{{ book.name }}</h1>

         <div>

                   {% for author in book.authors.all %}   #此處all後不用加(),否則文法錯誤

                   <li>{{ author }}</li>

                   {% endfor %}

         </div>

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

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

    url(r'^blog/register/$,'blog.views.register'),

from django import forms

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

         <form method='post'>

                   {{ form }}

         <input type='submit' value='ok'/>  

         </form>

13、

檔案上傳(方式一):

上傳檔案完成綁定動作,需兩步:

        uf = UserForm(req.POST,req.FILES)   #views.py

                   <form method='post' enctype='multipart/form-data'>   #register.html

]# django-admin.py startproject web07

]# cd !$

    username = forms.CharField()

    headimg = forms.FileField()

        # 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')

        uf = UserForm()

    return render_to_response('register.html',{'uf':uf})

]# mkdir blog/upload

         <div>\u7528\u6237\u6ce8\u518c</div>

                   <form method='post' enctype='multipart/form-data'>

                            {{ uf.as_p }}

                            <input type='submit' value='confirm'/>           

                   </form>  

views.py檔案中定義背景列印:

            print uf.cleaned_data['headimg'].name

            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

        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.

        'NAME': 'web08.db',                      # Or path to database file if using sqlite3.

MEDIA_ROOT = '/headImg'

    username = models.CharField(max_length=30)

    headimg = models.FileField(upload_to='./upload/')

        return self.username

    url(r'^blog/register/$','blog.views.register'),

from django.models import User

Creating table django_admin_log

]# sqlite3 web08.db

auth_group                  auth_user_user_permissions

auth_message                django_admin_log          

auth_user_groups            django_site  

sqlite> .exit

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,如需轉載請自行聯系原作者