基於上次創建ManyToMany關係的模型之後,現在看這些數據模型怎麼通過 views.py呈現
#修改urls.py 把地址 http://127.0.0.1/blog/show_author 視圖方法定義到 blog.views.show_author
vim csvt06/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'csvt06.views.home', name='home'), # url(r'^csvt06/', include('csvt06.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^blog/show_author$', 'blog.views.show_author'), )
#修改視圖模塊,定義方法 show_author
vim blog/views.py
from blog.models import Author, Book from django.shortcuts import render_to_response def show_author(req): authors = Author.objects.all() return render_to_response('show_author.html',{'authors':authors})
#創建模板,輸出傳遞的變量看是否有問題
mkdir blog/templates && vim blog/templates/show_author.html
`authors`
#上面輸出沒有問題之後,編輯模板文件,這裏使用了 for循環關於模板的更多使用方法可以參考
https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#
vim blog/show_author.html
{% for author in authors %} <div> <h3>`author`</h3> {% for book in author.book_set.all %} <li>`book`</li> {% endfor %} </div> {% endfor %}
#瀏覽器訪問之後顯示如下
#上面頁面是根據author 和該author所對應的書籍,既然是ManyToMany的關係,下面就在根據Book輸出Author,增加的步驟和上邊一樣
#
vim csvt06/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'csvt06.views.home', name='home'), # url(r'^csvt06/', include('csvt06.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), url(r'^blog/show_author$', 'blog.views.show_author'), url(r'^blog/show_book$', 'blog.views.show_book'), )
#
vim blog/views.py
from blog.models import Author, Book from django.shortcuts import render_to_response 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_book.html
{% for book in books %} <div> <h3>`book`</h3> {% for book in book.authors.all %} <li>`book`</li> {% endfor %} </div> {% endfor %}
#瀏覽器訪問顯示如下: