URL管理
1、創建好Project后在全局配置文件中有一個urls.py這個模塊,該模塊主要管理本項目的全局url配置
2、每個APP也應該創建一個urls.py模塊來管理自己APP下的url集(可選)
全局urls.py配置
主要注意的是
1、需要import include模塊
2、在urlpatterns中添加app下的urls模塊, namespace 參數可以防止不同app下的 url name
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace="blog")), ]
APP下的urls.py
1、import django中url模塊
2、import app中的views模塊
3、需要注意的是url是以正則表達式來配置管理,訪問web頁面的url = 全局url+APP url
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name="index"), ]
URL.py中的正則表達式
這里需要注意的是:
1、如果正則里面有()括號表示為分組,會自動將()括號里面的內容傳到views.article_page視圖中。
2、如果正則格式為:(?P<>) 表示為命名分組,在View視圖里面或者template調用的時候,可以直接使用命名去調用
在url.py中我們可以使用正則表達式來匹配url
urlpatterns = [ url(r'^$', views.index), url(r'^article/(?P<article_id>[0-9]+)$', views.article_page), ]
其中(?P<article_id>[0-9]+)不是很好理解,先來看看re官方的解釋:
“(?P<name>...) 子串匹配到的內容將可以用命名的name來提取url中的值。組的name必須是有效的python標識符,而且在本表達式內不重名。”
Templates href格式
href="{% url ‘app_name:url_name’ param %}"
app_name和url_name中需要在全局的urls.py和app下的urls.py中配置好
兩種方式:
第一種
第二種
#第一步在app-url.py的url中添加一個name參數:name='app-views-func' urlpatterns = [ url(r'^$', views.index), url(r'^article/(?P<article_id>[0-9]+)$', views.article_page, name='blog-views-article_page'), ] #第二步在Template中編寫href href="{% url 'blog-views-article_page' article.id %}"
正則表達是的命名分組(?P<>)
1、簡單分組
from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/([0-9]{4})/$', views.year_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]
2、有名分組(有名分組就可以在views.py中通過 關鍵字參數 year, month,day)
from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive), url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail), ]
應用案例:
urls.py 相關代碼:
url(r'^bookdetail/(?P<book_id>\d+)/$', BookDetailView.as_view(), name='bookdetail'),
Views.py代碼: 從url中接收book_id
class BookDetailView(View): """ 圖書詳情 """ def get(self, request, book_id): book_detail = Book.objects.get(id=int(book_id)) return render(request, "book_detail.html", {"book_detail": book_detail})
HTML代碼:
<table class="table table-hover"> <thead> <tr> <th>No.</th> <th>書名</th> <th>作者</th> <th>出版日期</th> <th>定價</th> </tr> </thead> <tbody> {% for book in all_books.object_list %} <tr> <td>{{ forloop.counter }}</td> <td><a href="{% url "bookdetail" book.id %}">{{ book.name }}</a></td> <td>{{ book.author }}</td> <td>{{ book.publish_date|date:"Y-m-d" }}</td> <td>{{ book.price|floatformat:2 }}</td> </tr> {% empty %} <tr> <td>暫無圖書</td> </tr> {% endfor %} </tbody> </table>