Skip to content

Instantly share code, notes, and snippets.

@nwjlyons
Created October 14, 2019 10:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjlyons/88d763f27b137ccb3f6638e59ac5bc58 to your computer and use it in GitHub Desktop.
Save nwjlyons/88d763f27b137ccb3f6638e59ac5bc58 to your computer and use it in GitHub Desktop.
Django Date Path Converter
from datetime import datetime, date
class DateConverter:
regex = '[0-9]{4}-[0-9]{2}-[0-9]{2}'
def to_python(self, value: str):
return datetime.strptime(value, '%Y-%m-%d').date()
def to_url(self, value: date):
return value.strftime('%Y-%m-%d')
@nwjlyons
Copy link
Author

# urls.py
import path_converters

register_converter(path_converters.DateConverter, 'date')

urlpatterns = [
    path('<date:date>/<slug:slug>/', views.ArticleDetail.as_view()),
]

Date object will be passed to view function/method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment