首页 > 解决方案 > 如何让这个 url 模式匹配?

问题描述

我正在努力将 url 与 pk 以外的 args 匹配。我有一个具有属性年份和会话的季节模型:

 class Season(models.Model):
     season_choices = SEASON_CHOICES
     current = models.BooleanField(default=False)
     year = models.IntegerField(_('year'), choices=year_dropdown, default=datetime.datetime.now().year)
     session = models.CharField(max_length=100, null=True, blank=True, choices=season_choices)

我想匹配诸如季节/年份/会话之类的网址。我有一个列出所有季节的列表视图:

 class SeasonList(ListView):
     model = Season
     template_name = 'team/season_list.html'

     def get_queryset(self):
         s = SeasonModel.objects.filter()
         return s

和一个应该显示季节细节的detailview。

  class SeasonDetail(DetailView):
     model = Season
     template_name = 'team/season_detail.html'

     def get_object(self, *args, **kwargs):
         season = get_object_or_404(Season, year=self.kwargs['year'], session=self.kwargs['session'])
         return season

这是我的网址:

 url(r'^season/$', team_views.SeasonList.as_view(), name='season_list'),
 url(r'^season/(?P<year>[0-9]{4})/(?P<session>[-\w]+)/$', team_views.SeasonDetail.as_view(), name='season_detail'),

最后是我的模板链接:

 <a href="{% url 'team:season_detail' year=season.year session=season.session %}">
 <p>{{ season.year }} {{ season.session }}</p></a>

标签: htmldjangopython-3.x

解决方案


推荐阅读