例子以上一篇随笔中的blog应用进行.
urls.py默认生成的格式如下:
1 """whsweb URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/1.8/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: url(r‘^$‘, views.home, name=‘home‘) 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: url(r‘^$‘, Home.as_view(), name=‘home‘) 12 Including another URLconf 13 1. Add an import: from blog import urls as blog_urls 14 2. Add a URL to urlpatterns: url(r‘^blog/‘, include(blog_urls)) 15 """ 16 from django.conf.urls import include, url 17 from django.contrib import admin 18 19 urlpatterns = [ 20 url(r‘^admin/‘, include(admin.site.urls)), 21 ]
第一种方式:应用.视图.方法
url(r‘^blog/index/$‘,‘blog.views.archive‘)
这个就表示访问url匹配r‘^blog/index/$‘正则表达式的情况下,网页呈现blog应用下views视图中的archive方法
第二用方式:调用对象
头部导入对象:
from blog.views import archive
url(r‘^blog/index/$‘,archive)
第三种方式:构建patterns赋值
头部记得导入
from django.conf.urls import include, url,patterns使用patterns方法赋值给urlpatterns对象
urlpatterns =patterns(‘blog.views‘ url(r‘^blog/index/$‘,‘archive‘) )
第四种方式:包含其他url
url(r‘^blog/‘, include(‘blog.urls‘)),直接包含blog下的urls配置。
url方法:
def url(regex, view, kwargs=None, name=None, prefix=‘‘): if isinstance(view, (list, tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) else: if isinstance(view, six.string_types): warnings.warn( ‘Support for string view arguments to url() is deprecated and ‘ ‘will be removed in Django 2.0 (got %s). Pass the callable ‘ ‘instead.‘ % view, RemovedInDjango20Warning, stacklevel=2 ) if not view: raise ImproperlyConfigured(‘Empty URL pattern view name not permitted (for pattern %r)‘ % regex) if prefix: view = prefix + ‘.‘ + view return RegexURLPattern(regex, view, kwargs, name)
可以看到url参数可以采用三种方式配置:1、list 2、tuple 3、string
include方法返回的是tuple
时间: 2024-10-06 15:32:02