urls.py的配置,在这里增加了template_name的参数:
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<key>.+)/$', "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"),
]
#采用pattern的写法,减少view的编写
urlpatterns += patterns("books.views",
url(r'^books/$', "book_route", name="books_book"),
url(r'^books/(?P<key>.+)/$', "book_detail", 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"}),
)
django_forms.views.py的配置
#coding=utf-8
from django.shortcuts import render
from .models import ContactUs
from .forms import ContactUsForm
from django.http import HttpResponse, HttpResponseRedirect
import logging
logger = logging.getLogger(__name__)
# Create your views here.
def contactus(request):
#return HttpResponse("<h1>这是一个测试</h1>")
#判断如果是GET则请求,否则作为POS处理
if request.method == "GET":
f = ContactUsForm()
else:
#这个地方必须要首先对Form进行绑定数据
#如果没有绑定数据,始终is_valid会返回false
#POST中包含绑定的数据
f = ContactUsForm(request.POST)
if f.is_valid():
s = f.cleaned_data["subject"]
c = f.cleaned_data["content"]
ex = f.cleaned_data["extra"]
email = f.cleaned_data["email"]
#直接将表单数据保存到数据库中
f.save()
#提交成功,数据进行重定向
#取出最后提交的数据对象
last_one = ContactUs.objects.order_by("-time")[0]
return HttpResponseRedirect("/contactus/thanks/?id=%d" % (last_one.id))
else:
logger.debug(f)
print(f.errors)
assert(False)
forms = f
return render(request,"django_forms/contactus.html", locals())
#对于网址路由,查询是额外的,但是注意书写,?查询之前记得加上路径分隔符/
def thanks(request, template_name):
contanctus_id = request.GET["id"]
if contanctus_id < 0:
return HttpResponseRedirect("无效ID")
#从数据库中取出数据来显示
content = ContactUs.objects.all().get(id=contanctus_id).content
return render(request,template_name, locals())