views.py
#coding=utf-8
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Book
# Create your views here.
"""
def book_route(request):
return render(request, "book.html",{"books":Book.objects.all()})
def book_detail(request, key):
book = Book.objects.all().get(id = key)
return render(request, "book_intro.html", {"book":book})
"""
class BookRoute(ListView):
model = Book
template_name = "book.html"
context_object_name = "books"
class BookDetail(DetailView):
model = Book
context_object_name = "book"
template_name = "book_intro.html"
#coding=utf-8
"""django_book URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls import patterns
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
#可以将这种格式精简成下面patterns的前缀格式
#url(r'^books/$', "books.views.book_route", name="books_book"),
#url(r'^books/(?P.+)/$', "books.views.book_detail", name="books_detail"),
#url(r'^contactus/$', "django_forms.views.contactus", name="django_form_contactus"),
#url(r'^contactus/thanks/', "django_forms.views.thanks", name="django_form_thanks"),
#使用include来实现,include下的子视图都会受到username的捕获参数
#使用include做前置匹配,不做后置匹配
#使用include来协同工作,最低降低了app的耦合度
#如果在这里使用额外参数kwargs={...},则include的所有views都会收到该参数
url(r'^(?P[a-zA-Z0-9]+)/blog/', include('advanced_views.urls')),
url(r'^generic/$', include('generic_views.urls')),
]
#采用pattern的写法,减少view的编写
from books.views import BookRoute, BookDetail
urlpatterns += patterns("books.views",
#url(r'^books/$', "book_route", name="books_book"),
url(r'^books/$', BookRoute.as_view(), name="books_book"),
#url(r'^books/(?P.+)/$', "book_detail", name="books_detail"),
#这个地方必须使用数据库表中的字段名称(pk是默认实现的主键)
#该字段会自动用来筛选出某个数据项,并将数据项传递给context_object_name
url(r'^books/(?P.+)/$', BookDetail.as_view(), name="books_detail"),
)
#django_forms的views
urlpatterns += patterns("django_forms.views",
url(r'^contactus/$', "contactus", name="django_form_contactus"),
url(r'^contactus/thanks/', "thanks", name="django_form_thanks", kwargs={"template_name":"django_forms/thanks.html"}),
)