[英]Django custom URL mapping: date pattern not matched in template
I am using Django 3.2我正在使用 Django 3.2
I have created a custom Date URL pattern matcher as follows:我创建了一个自定义 Date URL 模式匹配器,如下所示:
from datetime import datetime
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
from django.urls import path, register_converter
from . import views
from myproj.helpers import DateConverter
app_name = 'event'
register_converter(DateConverter, 'yyyymmdd')
urlpatterns = [
path('', views.index, name='index'),
path('detail/<int:event_id>/<slug:event_slug>', views.detail, name='detail'),
path('archive/<yyyymmdd:start_date>/<yyyymmdd:end_date>', views.archive, name='archive'),
]
<div class="row">
<a href="{% url 'event:archive' '2020101' '2020201' %}">Previous Events</a>
</div>
I get the following error:我收到以下错误:
reverse for 'archive' with arguments '('2020101', '2020201')' not found.
未找到带有 arguments '('2020101', '2020201')' 的“存档”的反向。 1 pattern(s) tried: ['media/events/archive/(?P<start_date>\d{4}\d{2}\d{2})/(?P<end_date>\d{4}\d{2}\d{2})$']
尝试了 1 种模式:['media/events/archive/(?P<start_date>\d{4}\d{2}\d{2})/(?P<end_date>\d{4}\ d{2}\d{2})$']
How do I fix this?我该如何解决?
Is it possible you're not passing enough digits in?有没有可能你没有传递足够的数字? Your DateConverter requires 4 + 2 + 2 = 8 digits and the numbers you are passing in only have 7 digits.
您的 DateConverter 需要 4 + 2 + 2 = 8 位数字,而您传入的数字只有 7 位数字。
Your date strings are wrong.你的日期字符串是错误的。 Indeed, it is interpreted as:
事实上,它被解释为:
2020101
YYYYMMDD
It is thus missing a digit for the month, a correct date thus looks like:因此,月份缺少一个数字,因此正确的日期如下所示:
{% url 'event:archive'
'20200101'
'20200201' %}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.