Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django url that captures yyyy-mm-dd date

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.

like image 287
PythonAnywhere Avatar asked Dec 18 '16 21:12

PythonAnywhere


People also ask

What does form {% URL %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

What is dynamic URL in Django?

Being able to capture one or more values from a given URL during an HTTP request is an important feature Django offers developers. We already saw a little bit about how Django routing works, but those examples used hard-coded URL patterns. While this does work, it does not scale.

What is Django URL reverse?

the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. Syntax: Web development, programming languages, Software testing & others. from django.urls import reverse.


2 Answers

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'),
]
like image 59
Ceribia Avatar answered Oct 15 '22 16:10

Ceribia


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

like image 35
Moses Koledoye Avatar answered Oct 15 '22 18:10

Moses Koledoye