我在为 Django 中的特定页面设置默认 url 时遇到了一些问题

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

现在我的 urls.py 设置如下:

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

我想要的是让 'month' 参数可选并默认为今天的月份。现在我的 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()
        month = self.kwargs['month']
        context['month'] = get_month(month)
        
        return context

def get_month(month):
    if month:
        return month
    else:
        return datetime.today().month

我的 dividends.html 文件为

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

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

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

如果我导航到 /dividends/Oct/(或任何其他月份)它工作正常,但如果我只是去 /dividends/ 它给我

KeyError: 'month'

我做错了什么,我该如何解决?

首先,您需要检查 kwarg 'month' 是否存在,然后分配月份值,否则它将引发 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

你可以用非常简单的方式做到这一点,你不需要在你身上定义两个端点urls.py

(?P<month>\w+|)

所以你的 url 将是 :-

path('dividends/(?P<month>\w+|)/', views.DividendView.as_view(), name='dividendview'),