[python]Django學習筆記(基礎)

一、win7下,沒法使用 django-admin.py startproject mysite創建工程。html

這是django的一個bug,網上說能夠經過修改註冊表解決,但嘗試後不行。最後可以使用python c:django-1.5.8/django/bin/django-admin.py startproject mysite成功創建了工程。python

 

二、修改環境變量後沒法直接使用django-admin.py。mysql

修改環境變量後,須要重啓電腦才能生效。web

 

三、視圖與URL配置相關(通常內容參見第三章內容)正則表達式

(1)在views.py中新建一個視圖。視圖其實就是一個py函數,一個函數對應一個request,返回一個response。sql

(2)注意:views.py是創建在第二層項目文件夾中,跟url.py在同一層,而不是跟manage.py在同一層。shell

(3)在urls.py中添加映射數據庫

from django.conf.urls.defaults import *
from mysite.views import hello

urlpatterns = patterns('',
    ('^hello/$', hello),
)

文件夾中的views.py對應成工程mysite的一個模塊,函數hello()從對應的模塊導入django

(4)映射經過正則表達式匹配,通常須要匹配開頭與結尾。服務器

(5)最後,凡是本站域名128.0.0.1:8000/hello/的都映射到hello函數進行response。(正則表達式規定了url以hello/開頭和結尾)

 

四、django模板相關

(1)模板中{{ }}表明變量;

 {% %}爲模板標籤,用於通知模板完成某種工做;有if標籤、for標籤等,用法與C語言的差很少;

 

(2)使用模板出錯:沒法使用t = template.Template('My name is {{ name }}.')

解決:先導入from django.conf import settings,再運行settings.configure()

緣由:

   轉到project目錄(在第二章由 django-admin.py startproject 命令建立), 輸入命令 python manage.py shell啓動交互界面。

  若是你曾經使用過Python,你必定好奇,爲何咱們運行 python manage.py shell 而不是 python 。這兩個命令都會啓動交互解釋器,可是 manage.py shell 命令有一個重要的不一樣: 在啓動解釋器以前,它告訴Django使用哪一個設置文件。 Django框架的大部分子系統,包括模板系統,都依賴於配置文件;若是Django不知道使用哪一個配置文件,這些系統將不能工做。
  若是你想知道,這裏將向你解釋它背後是如何工做的。 Django搜索DJANGO_SETTINGS_MODULE環境變量,它被設置在settings.py中。例如,假設mysite在你的Python搜索路徑中,那麼DJANGO_SETTINGS_MODULE應該被設置爲:’mysite.settings’。
  當你運行命令:python manage.py shell,它將自動幫你處理DJANGO_SETTINGS_MODULE。 在當前的這些示例中,咱們鼓勵你使用`` python manage.py shell``這個方法,這樣能夠免去你大費周章地去配置那些你不熟悉的環境變量。
 

(3)定義一個context,用於與模板的標籤映射

>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Adrian'})
>>> print t.render(c)
My name is Adrian.

能夠在template裏面直接調用類的屬性,而後在context中映射類對象便可(使用字典的鍵與值也同樣),如

>>> d = datetime.date(1993, 5, 2)
>>> d.year
1993
>>> d.month
5
>>> d.day
2
>>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.')
>>> c = Context({'date': d})
>>> t.render(c)
u'The month is 5 and the year is 1993.'

也能夠調用該類的方法,但注意,只能調用沒有參數的方法,調用時使用.method的形式,不用添加括號。

使用列表做爲tab也能夠,使用list.2的方式調用,表示調用列表第二個項

 

五、標籤相關

(1)標籤中的if語句,else可選,並可使用邏輯判斷(PS:同一標籤不能同時出現and 和 or)

{% if today_is_weekend and today_is_sunday %}
    <p>Welcome to the weekend!</p>
{% else %}
    <p>Get back to work.</p>
{% endif %}

(2)for標籤

{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}

in後必須是可迭代對象。可在最後加上reversed反向遍歷;for能夠嵌套;

for還有一個可選的empty分句,能夠在對象爲空時顯示,以下

{% for athlete in athlete_list %}
    <p>{{ athlete.name }}</p>
{% empty %}
    <p>There are no athletes. Only computer programmers.</p>
{% endfor %}

每一個for循環中有個forloop.counter(或forcounter0,從0開始計數),從1開始計數,記錄循環進行到第幾回;還有一個forloop.revcounter,開始時爲序列總數,每次遞減;forloop.first是一個布爾值,第一次迭代時爲真;forloop.last最後一次迭代時爲真。forloop.paraentloop是嵌套的上個for的forloop的引用。

{% for item in todo_list %}
    <p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}

(3)比較是否相等

{% ifequal user currentuser %}
    <h1>Welcome!</h1>
{% endifequal %}

也能夠添加else分句;

 

六、多行註釋

{% comment %}
This is a
multi-line comment.
{% endcomment %}

 

七、過濾器

過濾器使用管道符號|來鏈接,被處理的對象放在最前,後面能夠一次添加管道;有的管道會包含參數,參數使用雙引號「」包圍;

 

八、模板使用

爲了把網頁設計模板與python代碼分離,可在項目文件夾下新建templates文件夾,並使用get_template來加載模板,必須在settings.py中添加TEMPLATE_DIRS指定模板目錄

TEMPLATE_DIRS=( 'E:/djangodev/mysite/mysite/templates', )

模板的使用以下

from django.template.loader import get_template
from django.template import Context

def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)

更方便的返回一個渲染模板:render_to_response()

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

若是在指定的templates下有子文件夾,則在gettemplates和rendertoresponse時添加相對路徑便可,如

t = get_template('apptemplates/current_datetime.html')

 

在模板中添加其餘模板的內容(通常是一些經常使用的模板),可使用include

<html>
<body>
{% include "includes/nav.html" %}
<h1>{{ title }}</h1>
</body>
</html>

 

九、模板重載

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>

使用block標籤來表明子模板能夠重載的部分,每一個block能夠起一個名字

使用extend來繼承父模板,子模板只是寫出與父模板不一樣之處便可

{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}

 

你能夠根據須要使用任意多的繼承次數。 使用繼承的一種常見方式是下面的三層法:

 (1)建立  base.html 模板,在其中定義站點的主要外觀感覺。 這些都是不常修改甚至從不修改的部分。
(2)爲網站的每一個區域建立  base_SECTION.html 模板(例如,  base_photos.html 和  base_forum.html )。這些模板對 base.html 進行拓展,幷包含區域特定的風格與設計。
(3)爲每種類型的頁面建立獨立的模板,例如論壇頁面或者圖片庫。 這些模板拓展相應的區域模板。
如下是使用模板繼承的一些訣竅:
(1)若是在模板中使用  {% extends %} ,必須保證其爲模板中的第一個模板標記。 不然,模板繼承將不起做用。
(2)通常來講,基礎模板中的  {% block %}  標籤越多越好。 記住,子模板沒必要定義父模板中全部的代碼塊,所以你能夠用合理的缺省值對一些代碼塊進行填充,而後只對子模板所需的代碼塊進行(重)定義。 俗話說,鉤子越多越好。
(3)若是發覺本身在多個模板之間拷貝代碼,你應該考慮將該代碼段放置到父模板的某個  {% block %}  中。
(4)若是你須要訪問父模板中的塊的內容,使用  {{ block.super }} 這個標籤吧,這一個魔法變量將會表現出父模板中的內容。 若是隻想在上級代碼塊基礎上添加內容,而不是所有重載,該變量就顯得很是有用了。
(5)不容許在同一個模板中定義多個同名的  {% block %}  。 存在這樣的限制是由於block 標籤的工做方式是雙向的。 也就是說,block 標籤不只挖了一個要填的坑,也定義了在 模板中這個坑所填充的內容。若是模板中出現了兩個相同名稱的  {% block %}  標籤,父模板將無從得知要使用哪一個塊的內容。
(6){% extends %}  對所傳入模板名稱使用的加載方法和  get_template()  相同。 也就是說,會將模板名稱被添加到  TEMPLATE_DIRS  設置以後。
(7)多數狀況下,  {% extends %}  的參數應該是字符串,可是若是直到運行時方能肯定父模板名,這個參數也能夠是個變量。 這使得你可以實現一些很酷的動態功能。
 
十、鏈接mysql數據庫
(1)安裝數據庫引擎mysqldb
(2)配置setting.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'iyjhabc',
        'PASSWORD': '',
        'HOST': '', 
        'PORT': '',   
    }
}

(3)在mysite下建立一個app

python manage.py startapp books

(4)在app的models.py下使用函數的形式填寫表信息

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    website = models.URLField()

(5)修改setting.py激活APP

INSTALLED_APPS = (
    # 'django.contrib.auth',
    # 'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    # 'django.contrib.sites',
    'books',//書上此處錯誤
)

(6)檢驗模型有效性

python manage.py validate

(7)生成SQL語句。PS:此時並未在數據庫使用這些SQL語句

python manage.py sqlall books

(8)把models.py的內容同步到數據庫。PS:若是models.py中的表還沒有新建,則同步會新建這些表,若是對錶進行了修改,則同步不會修改這些表。

python manage.py syncdb

 (9)使用以前已經定義好的 Model的子類Pubilisher來把數據添加到數據庫

>>> from books.models import Publisher
>>> p1 = Publisher(name='Apress', address='2855 Telegraph Avenue',
...     city='Berkeley', state_province='CA', country='U.S.A.',
...     website='http://www.apress.com/')
>>> p1.save()

注意,只有使用save()的時候才正式將數據寫入數據庫。

(10)直接使用create()函數就能夠一次進行填寫數據和寫數據庫的功能

>>> p1 = Publisher.objects.create(name='Apress',
...     address='2855 Telegraph Avenue',
...     city='Berkeley', state_province='CA', country='U.S.A.',
...     website='http://www.apress.com/')

 

十一、數據庫查詢等操做

可使用fliter()進行SQL的where操做

>>> Publisher.objects.filter(name='Apress')

也能夠傳遞多個參數給fliter,至關於使用SQL的and

Publisher.objects.filter(country="U.S.A.", state_province="CA")

使用contains進行模糊查詢,XX 兩個下劃線 contains,至關於like

Publisher.objects.filter(name__contains="press")

fliter是獲取一個結果集,使用get()獲取單個對象,當查詢到0個或者多於1個結果是,會拋出異常

Publisher.objects.get(country="U.S.A.")

使用orderby來排序,逆序的話在排序項目前面加「-」

Publisher.objects.order_by("name")
Publisher.objects.order_by("-name")

連鎖查詢,至關於添加多個條件的SQL語句

Publisher.objects.filter(country="U.S.A.").order_by("-name")

使用python列表分片的形式能夠提取結果的部分,以下是提取第一個元素

Publisher.objects.filter(country="U.S.A.")[0]

 

十二、數據庫更新

 若是要修改一個數據項,則不使用save(),由於他會更新全部數據項,使用update()

>>> Publisher.objects.filter(id=52).update(name='Apress Publishing')

也能夠對包含多個紀錄的子集進行更新,返回受影響子集個數

>>> Publisher.objects.all().update(country='USA')
2

輸出數據,delete()

 Publisher.objects.filter(country='USA').delete()

 

1三、建立admin站點管理頁面

Activating the Admin Interface

The Django admin site is entirely optional, because only certain types of sites need this functionality. That means you’ll need to take a few steps to activate it in your project.

First, make a few changes to your settings file:

  1. Add 'django.contrib.admin' to the INSTALLED_APPS setting. (The order of INSTALLED_APPS doesn’t matter, but we like to keep things alphabetical so it’s easy for a human to read.)
  2. Make sure INSTALLED_APPS contains 'django.contrib.auth''django.contrib.contenttypes','django.contrib.messages' and 'django.contrib.sessions'. The Django admin site requires these three packages. (If you’re following along with our ongoing mysite project, note that we commented out these four INSTALLED_APPS entries in Chapter 5. Uncomment them now.)
  3. Make sure MIDDLEWARE_CLASSES contains 'django.middleware.common.CommonMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.contrib.sessions.middleware.SessionMiddleware' and'django.contrib.auth.middleware.AuthenticationMiddleware'. (Again, if you’re following along, note that we commented them out in Chapter 5, so uncomment them.)

Second, run python manage.py syncdb. This step will install the extra database tables that the admin interface uses. The first time you run syncdb with 'django.contrib.auth' in INSTALLED_APPS, you’ll be asked about creating a superuser. If you don’t do this, you’ll need to run python manage.py createsuperuser separately to create an admin user account; otherwise, you won’t be able to log in to the admin site. (Potential gotcha: thepython manage.py createsuperuser command is only available if 'django.contrib.auth' is in your INSTALLED_APPS.)

Third, add the admin site to your URLconf (in urls.py, remember). By default, the urls.py generated bydjango-admin.py startproject contains commented-out code for the Django admin, and all you have to do is uncomment it. For the record, here are the bits you need to make sure are in there:

# Include these import statements...
from django.contrib import admin
admin.autodiscover()

# And include this URLpattern...
urlpatterns = patterns('',
    # ...
    (r'^admin/', include(admin.site.urls)),
    # ...
)

 

把models放入admin頁面管理

在該app books下的admin.py下,註冊各個模型

from django.contrib import admin

# Register your models here.
from books.models import Publisher, Author, Book

admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)

 

 1四、表單

使用表單通常就是使用HttpRequest,分爲GET和POST兩種方法,原理與以前學過的JAVA差很少,GET使用url的形式提交參數,POST使用tcp的方式經過服務器提交。值得關注的是HttpRequest類有很方法用於獲取用戶的信息,須要慢慢積累。

處理表單的流程: 頁面(urls.py)-> python 方法(處理表單數據) -> response(相應出一個結果頁面) 

使用到的頁面通常使用模板,並用讀取到的輸入數據和查詢結果填充模板。

 

 在文件夾中新建contact來存放聯繫相關的頁面,此時必須新建一個__init__.py的文件,不然python沒法找到contact下面的類。(也能夠用startapp命令來完成)

 

 

始終要明白,當經過一系列的數據來建立表單對象,並驗證經過的時候,就要使用cleaned_data屬性進行‘清理工做’,所謂的清理就是對給定的數據對應到python類型。返回的是一組被清理過的字典類型數據。

>>> boundF.cleaned_data
{'age': 22, 'name': u'BeginMan', 'email': u'xinxinyu2011@163.com'}

 

能夠在表單中使用隱藏項,用於記錄傳遞數據:當有數據須要傳遞給下一頁面,可定義隱藏表單項

article_id = forms.CharField(widget=forms.HiddenInput())

而後給這個項賦一個廚師值

edit_form = EditForm(initial={ 'article_id':article_id,})

下個頁面就能夠用GET讀取這個值

 

 1五、把菜單封裝成tag,並關聯響應函數

tage_pages.py

from django import template
register = template.Library()

@register.inclusion_tag('tags/landing_header.html', takes_context=True)
def landing_header(context, nav):
    return {'nav': nav, 'user': context['request'].user}

把landing_header這個tag與此函數與html文件關聯起來

 

使用landing_header這個tag的html頁面.html

 {% load tags_pages %} #加載tag所在的py文件
 {% recent_app_menu %} #使用tag,後可加空格帶參數

一個tag其實就是翻譯成一段帶模板的html代碼,不必定是一個完成的html頁面

相關文章
相關標籤/搜索