Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
Best practice for validating a date in url in django?

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!