Home > Software engineering >  Best practice for validating a date in url in django?
Best practice for validating a date in url in django?

Time:10-18

I have a logging system, where users can log several symptoms for any given day. Im getting the date as slug in my url, but I need to validate it. Which one is best practice, and why?

  1. make a validator function in the class view and use it there

  2. add a hidden form field, and write a custom DateValidator for it?

CodePudding user response:

You can define a path converter that will parse date objects. You can define a custom pattern with:

# app_name/converters.py

class DateConverter:
    regex = '[0-9]{4}-[0-9]{2}-[0-9]{2}'
    format = '%Y-%m-%d'

    def to_python(self, value):
        return datetime.strptime(value, self.format).date()

    def to_url(self, value):
        return value.strftime(self.format)

Next we can register that path converter [Django-doc] and work with:

from app_name.converters import DateConverter
from django.urls import path, register_converter

register_converter(DateConverter, 'date')

urlpatterns = [
    # …
    path('some/path/<date:date>/', some_view),
    # …
]

This will pass a single date parameter to the view, which is a date object, you thus can work with:

def some_view(request, date):
    # …

If you thus visit the path /some/path/2021-10-17, date will be a date(2021, 10, 17) object.

  • Related