現在我的 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
和我的股息.html檔案
{% extends 'base.html' %}
{% load static %}
{% block title %}Dividends{% endblock %}
{% block content %}
{{ month }}
{% endblock %}
如果我導航到 /dividends/Oct/(或任何其他月份)它作業正常,但如果我只是去 /dividends/ 它給了我
KeyError: 'month'
誰能幫我弄清楚我做錯了什么以及我如何解決它?
謝謝。
uj5u.com熱心網友回復:
首先,您需要檢查kwarg'month' 是否存在,然后分配月份值,否則它將引發keyError。
視圖.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
如果這對您有用,請接受答案。快樂編碼!
uj5u.com熱心網友回復:
你可以用非常簡單的方式來完成,你不需要在你的 urls.py 中定義兩個端點
(?P<month>\w |)
所以你的網址將是:-
path('dividends/(?P<month>\w |)/', views.DividendView.as_view(), name='dividendview'),
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326473.html
上一篇:Pyspark-歸一化資料框架
下一篇:作為函式引數的擴展介面實作
