django url 正则匹配

Page not found (404)
Request Method: 	GET
Request URL: 	http://192.168.137.3:8000/articles/2018

Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:

    ^admin/
    ^learn/
    ^add/
    ^articles/ ^articles/([0-9]{4})/$
    ^articles/ ^articles/([0-9]{4})/([0-9]{2})/$
    ^articles/ ^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$

The current path, articles/2018, didn't match any of these.




def year_archive(req,year):
    now = datetime.datetime.now()
    html = "call year_archive" +' '+ year
    return HttpResponse(html)

http://192.168.137.3:8000/articles/8888/  这里的8888是作为参数传递的


上面的代码将URLs映射作为简单的正则表达式映射到Python的回调(视图),

正则表达式通过圆括号来"捕获"URLs中的值,

当一个用户请求一个页面时,Django将按照顺序去匹配每一个模式,并停在第一个匹配请求的URL上。


http://192.168.137.3:8000/articles/8888/44/

call month_archive 8888 44


def month_archive(req,year,month):
    html = "call month_archive" +' '+ year +' ' + month
    return HttpResponse(html)



def year_archive(req,year):
    now = datetime.datetime.now()
    html = "call year_archive" +' '+ year
    return HttpResponse(html)

def month_archive(req,year,month):
    html = "call month_archive" +' '+ year +' ' + month
    return HttpResponse(html)

def article_detail(req,year,month,day):
    html = "call article_detail" +' '+ year +' ' + month +' '+day
    return HttpResponse(html)
	
http://192.168.137.3:8000/articles/8888/44/

call year_archive 8888

此时就匹配了第一条,而不是第2条	
原文地址:https://www.cnblogs.com/hzcya1995/p/13349135.html