Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

427
Vistas
I'm having some trouble setting default url for specific page in Django

Right now I have my urls.py set up like this:

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

What I would like is to have the 'month' parameter optional and default to today's month. Right now I have my views.py set up as

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

and my dividends.html file as

{% extends 'base.html' %}
{% load static %}

{% block title %}Dividends{% endblock %}

{% block content %}
    {{ month }}
{% endblock %}

If I navigate to /dividends/Oct/ (or any other month) it works fine, but if I just go to /dividends/ it gives me

KeyError: 'month'

What am I doing wrong and how might I go about fixing it?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

First, you need to check if the kwarg 'month' exists and then assign the month value else it will raise keyError.

Views.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 Denunciar

0

You can do it in very simply way and you dont need to define two endpoints in you urls.py

(?P<month>\w+|)

So your url will be :-

path('dividends/(?P<month>\w+|)/', views.DividendView.as_view(), name='dividendview'),
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda