Home > database >  I'm having some trouble setting default url for specific page in Django
I'm having some trouble setting default url for specific page in Django

Time:10-20

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'

Can anyone help me figure out what I'm doing wrong and how I might go about fixing it?

Thanks.

CodePudding user response:

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

Please accept the answer if this works for you. Happy coding!

CodePudding user response:

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'),
  • Related