Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

309
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda