您的位置:首页 > 编程语言 > Go语言

django在urlconf中使用include

2015-11-29 15:57 495 查看
根文件urls.py

#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<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"),

#使用include来实现,include下的子视图都会受到username的捕获参数
#使用include做前置匹配,不做后置匹配
url(r'^(?P<username>[a-zA-Z0-9]+)/blog/', include('advanced_views.urls')),
]

#采用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"}),
)


advanced_views.urls.py

#coding=utf-8

from django.conf.urls import patterns, url
urlpatterns = patterns("advanced_views.views",
url(r'^$', "index", name="advanced_views_index"),
url(r'^articles$', "articles", name="advanced_views_articles"),
)


advanced_views.views.py

<pre name="code" class="python">#coding=utf-8

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
#特别要注意的是username的编码格式是unicode的,如果使用参数要注意
#捕捉参数的编码格式传过来都是unicode编码的
def index(request, username):
#正确写法:将unicode编码转换为本文件一样的编码格式(utf-8)
return HttpResponse("<h1>Urlconf的include演示:username=%s</h1>" % (username.encode("utf-8"),))
#正确写法:使用unicode字符串
#return HttpResponse(u"<h1>Urlconf的include演示:username=%s</h1>" % (username,))

#错误的写法:因为username和字符串的编码不一致,一个是utf-8一个是unicode没法格式化
#return HttpResponse("<h1>Urlconf的include演示:username=%s</h1>" % (username,))



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: