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().monthy 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?
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 contextPuede 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'),