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

440
Views
Tengo problemas para configurar la URL predeterminada para una página específica en Django

En este momento tengo mi urls.py configurado así:

 urlpatterns = [ ... path('dividends/<str:month>/', views.DividendView.as_view(), name='dividendview'), path('dividends/', views.DividendView.as_view(), name='dividendview'), ]

Lo que me gustaría es tener el parámetro 'mes' opcional y predeterminado para el mes de hoy. En este momento tengo mi views.py configurado como

 class DividendView(ListView): model = Transaction template_name = 'por/dividends.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) divs = Dividends() month = self.kwargs['month'] context['month'] = get_month(month) return context def get_month(month): if month: return month else: return datetime.today().month

y mi archivo dividends.html como

 {% extends 'base.html' %} {% load static %} {% block title %}Dividends{% endblock %} {% block content %} {{ month }} {% endblock %}

Si navego a /dividends/Oct/ (o cualquier otro mes) funciona bien, pero si solo voy a /dividends/ me da

 KeyError: 'month'

¿Qué estoy haciendo mal y cómo podría solucionarlo?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Primero, debe verificar si existe el 'mes' de kwarg y luego asignar el valor del mes; de lo contrario, generará keyError .

Vistas.py

 class DividendView(ListView): model = Transaction template_name = 'por/dividends.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) divs = Dividends() if 'month' in self.kwargs: # check if the kwarg exists month = self.kwargs['month'] else: month = datetime.today().month context['month'] = month return context
over 4 years ago · Santiago Trujillo Report

0

Puede hacerlo de una manera muy simple y no necesita definir dos puntos finales en su urls.py

(?P<month>\w+|)

Entonces tu URL será: -

 path('dividends/(?P<month>\w+|)/', views.DividendView.as_view(), name='dividendview'),
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!