码迷,mamicode.com
首页 > 编程语言 > 详细

python--Django(三)视图

时间:2018-09-04 23:30:25      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:引入   其他   mes   指定   views   namespace   rgs   mode   python   

Django的视图

不同于其他语言的MVC模式,Django采用的是MVT模式,即Model、View、Template,这里的View其实质就是其他语言中的Controller(emmm.....),而Template其实就是html文件,所以原理其实大同小异,这里就不多赘述

配置URL

Django中的默认路由在项目主目录下的urls.py中,基本路由配置如下所示:

from django.urls import path, include
from . import views

urlpatterns = [
    path(‘articles/2003/‘, views.special_case_2003),
    path(‘articles/<int:year>/‘, views.year_archive),
    path(‘articles/<int:year>/<int:month>/‘, views.month_archive),
    path(‘articles/<int:year>/<int:month>/<slug:slug>/‘, views.article_detail),
    path(‘‘, include(‘test.urls‘))                                                                                # 引入不同应用的url配置
]

以上为普通匹配方式,其中有几种能够限制路由中参数类型的函数可以使用。

  • str: 匹配除路径分隔符‘/‘之外的任何非空字符串
  • int:匹配零或任何正整数
  • slug:匹配由ASCII字母或数字组成的任何slug字符串,以及连字符‘-‘和下划线‘_‘字符
  • uuid:匹配格式化的UUID
  • path:匹配任何非空字符串,包括路径分隔符 ‘/‘

使用正则表达式匹配

from django.urls import path, re_path

from . import views

urlpatterns = [
    path(‘articles/2003/‘, views.special_case_2003),
    re_path(r‘^articles/(?P<year>[0-9]{4})/$‘, views.year_archive),                                                                        # ?P<year>意为指定参数的名字
    re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$‘, views.month_archive),
    re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$‘, views.article_detail),
]

URL起别名
此例相对于PHP laravel框架中的route()用法,具体用法如下

# 路由中的配置
from django.urls import path, include
from test import views

urlpatterns = [
    path(‘‘, views.index, name=‘test-index‘),
    path(‘/<int:num>‘, views.getNum)
    path(‘‘, include(‘test.urls‘, namespace = ‘test‘))            #为include起别名
]

# 在template中的运用
<a href="{% url ‘test-index‘ 此处可以跟参数 %}"></a>

# 在views中的运用
from django.http import HttpResponseRedirect
from django.urls import reverse

def redirect_to_year(request):
    year = 2006                                                                                                                                # 参数
    return HttpResponseRedirect(reverse(‘test-index‘, args=(year,)))

python--Django(三)视图

标签:引入   其他   mes   指定   views   namespace   rgs   mode   python   

原文地址:https://www.cnblogs.com/peilanluo/p/9589039.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!