天天看點

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

1、win7下,無法使用 django-admin.py startproject mysite建立工程。

這是django的一個bug,網上說可以通過修改系統資料庫解決,但嘗試後不行。最後可使用python c:django-1.5.8/django/bin/django-admin.py startproject mysite成功建立了工程。

2、修改環境變量後無法直接使用django-admin.py。

修改環境變量後,需要重新開機電腦才能生效。

3、視圖與URL配置相關(一般内容參見第三章内容)

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

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

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

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

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

檔案夾中的views.py對應成工程mysite的一個子產品,函數hello()從對應的子產品導入

(4)映射通過正規表達式比對,一般需要比對開頭與結尾。

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

4、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的方式調用,表示調用清單第二個項

5、标簽相關

(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分句;

6、多行注釋

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

7、過濾器

過濾器使用管道符号|來連接配接,被處理的對象放在最前,後面可以一次添加管道;有的管道會包含參數,參數使用雙引号“”包圍;

8、模闆使用

為了把網頁設計模闆與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>      

9、模闆重載

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html 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 %}  的參數應該是字元串,但是如果直到運作時方能确定父模闆名,這個參數也可以是個變量。 這使得你能夠實作一些很酷的動态功能。   10、連接配接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/')      

11、資料庫查詢等操作

可以使用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]      

12、資料庫更新

 如果要修改一個資料項,則不使用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()      

13、建立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)      

 14、表單

使用表單一般就是使用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'[email protected]'}      

可以在表單中使用隐藏項,用于記錄傳遞資料:當有資料需要傳遞給下一頁面,可定義隐藏表單項

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

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

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

下個頁面就可以用GET讀取這個值

 15、把菜單封裝成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頁面

轉載于:https://www.cnblogs.com/iyjhabc/p/3856450.html