我正在尝试将网址参数传递给我的应用中的另一个view
。我目前有一个功能(EntryListView
),用于标识您选择的月份,然后仅显示该月份的内容。但是,我希望这个月也会显示在detail
网址中。这将使“返回”按钮能够导航回月份页面,而不是错误输出或导航回登录页面。
urls.py按原样:
url(r'entry/list/(?P<month>\w+)$', views.EntryListView.as_view(), name='entry-list'),
url(r'entry/detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
views.py
class DetailView(generic.DetailView):
model = Entry
template_name = 'argent/detail.html'
class EntryListView(generic.ListView):
template_name = 'argent/index_list.html'
queryset = Entry.objects.all()
def get_context_data(self, **kwargs):
month = self.kwargs.get('month')
ctx = super(EntryListView, self).get_context_data(**kwargs)
# January
if month == 'January':
ctx['January17_qs'] = Entry.objects.filter(date__range=('2017-1-1', '2017-1-31'))
# February17
elif month == 'February':
ctx['February17_qs'] = Entry.objects.filter(date__range=('2017-2-1', '2017-2-28'))
# March
elif month == 'March':
ctx['March17_qs'] = Entry.objects.filter(date__range=('2017-3-1', '2017-3-31'))
return ctx
模板
<a href="{% url 'argent:entry-list' %}">
<button type="button" class="btn btn-primary">Go Back
</button>
</a>
使用{% url 'argent:entry-list' %}
时,我目前收到此错误:
Reverse for 'entry-list' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tracker/entry/list/(?P<month>\\w+)$']
提前感谢您的帮助!
答案 0 :(得分:2)
您可以将详细信息的月份作为kwarg传递给url
模板标记。这样的事情应该有效。
class DetailView(generic.DetailView):
model = Entry
template_name = 'argent/detail.html'
def get_context_data(self, **kwargs):
ctx = super(DetailView, self).get_context_data(**kwargs)
ctx['current_month'] = self.get_object().date.strftime("%B")
return ctx
template.html
<a href="{% url 'argent:entry-list' current_month %}">
<button type="button" class="btn btn-primary">Go Back</button>
</a>