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

425
Views
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 answers
Answer question

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 Report

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 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!