之前已經(jīng)創(chuàng)建完成了第一個project和app, 接下來說一下創(chuàng)建完成后該怎么做, 主要參考一下的是官方文檔
project和app的區(qū)別
官方文檔上是這樣說的:
What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.
一個app是用來完成一些特定功能的, 比如一個博客系統(tǒng), 一個簡單的投票系統(tǒng)等等,而一個項目是一些應用的集合. 簡單來說, 一個項目可以包含多個app, 一個app也是可以在多個項目中使用的
polls/views
接下來寫第一個view函數(shù), 在polls/views.py文件中:
from django.http import HttpResponse
def index(request):
return HttpResponse("主頁")
這是最簡單的一個view視圖函數(shù)了
polls/urls
使用startapp是沒有urls.py這個文件的, 所以需要自己create一個,
然后這樣寫:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index")
]
The next step is to point the root URLconf at the polls.urls module.
接下來要在mysite的urls.py中指向poll.urls
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
incldue()函數(shù)允許引用其他的URLconfs, 但是注意使用include的時候, 正則表達式不要以$ 結束, 而是應該以/ 結束, 因為:
it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
因為會將前面的匹配部分去掉, 將剩余的部分發(fā)送到include的URLconfs中
接下來運行一下, 在localhost:8000/polls就可以看見主頁兩個字了
When to use include()?
You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.
只要有其他的url patterns的時候, 就應該使用include, 除了admin.site.urls,
我使用版本和看的官方文檔的版本都是1.11, 所以如果看到include(admin.site.urls)的情況, 是因為版本不同
深入url()方法
url()函數(shù)有兩個必須的參數(shù), regex和view, 還有兩個參數(shù), kwargs和name
url() argument: regex
顯然, 這里是一個正則表達式, 這里是用來匹配url的
Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.
django會從第一個正則表達式開始, 一個個去匹配, 直到匹配到
Note that these regular expressions do not search GET and POST parameters, or the domain name.
注意這些正則表達式是不會匹配GET或者POST, 也不會匹配域名, 舉個栗子:
https://www.example.com/myapp/ 的結果是myapp/, https://www.example.com/myapp?page=6 的結果也是myapp/
這些正則表達式在第一次加載URLconf模塊的時候就被編譯, 它們很快
url() argument: view
當正則表達式匹配到的時候, 就會調用指定的view函數(shù)
url() argument: kwargs
Arbitrary keyword arguments can be passed in a dictionary to the target view.
這個估計暫時不會用到
url() argument: name
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.
命名url后可以在django其他地方引用