基于上次创建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 %}
#浏览器访问显示如下: