Django url that captures yyyy-mm-dd date

醉酒当歌 提交于 2021-01-14 16:33:11

问题


How do you capture a url that contains yyyy-mm-dd in Django. So like www.mydomain.com/2011-02-12. I tried:

url(r'^(?P<date>\d{4}-\d{2}-\d{2})/$', views.index, name='index'), 

But, the server says page not found.


回答1:


You should have a group name in the url pattern:

url(r'^(?P<date>\d{4}-\d{2}-\d{2})/$', views.index, name='index'),
#          ^^^^

Also pay attention to the trailing slash in the url: www.mydomain.com/2011-02-12/. If you don't want a slash in the url, you can remove it from the pattern.


And your view function would then take the name of the group as one of its parameters

def index(request, date):
    ...

You should see the docs on Django url named groups




回答2:


In Django 3.0.5 I did this using the following urls.py

from django.urls import path, register_converter
from datetime import datetime
from . import views

class DateConverter:
    regex = '\d{4}-\d{2}-\d{2}'

    def to_python(self, value):
        return datetime.strptime(value, '%Y-%m-%d')

    def to_url(self, value):
        return value

register_converter(DateConverter, 'yyyy')

urlpatterns = [
    path('', views.index, name='index'),
    path('date/<yyyy:date>/', views.date, name='date'),
]



回答3:


try this :

url(r'^(?P<date>[0-9]{4}-?[0-9]{2}-?[0-9]{2})/$', views.index, name='index'),


来源:https://stackoverflow.com/questions/41212865/django-url-that-captures-yyyy-mm-dd-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!