在 DetailView 中获取 Slug

Get Slug in DetailView

urls.py

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name="index"),
    url(r'^(?P<slug>[-\w]+)/$', views.DetailView.as_view(), name="detail"),
]

views.py

class DetailView(generic.DetailView):
    model = Company
    template_name = 'news/detail.html'

    def get_context_data(self, **kwargs):
         # Add in a QuerySet of all the books
         context = super(DetailView, self).get_context_data(**kwargs)
         response = requests.get('https://api.intrinio.com/news?identifier=SHOP', auth=requests.auth.HTTPBasicAuth(
        'xxxx',
        'xxxx'))
         context['articleList'] = response.json()
         return context

要访问的网址:http://localhost:8000/news/SHOP/

所以我的应用程序要做的是,根据 URL 检索 slug 并使用 Intrinio 的 API 来获得响应。

响应部分一切正常,但目前始终是同一家公司 (?identifier=SHOP)。我想根据 url.

使其动态化

但我对 Django 还很陌生,我不确定应该如何将 slug 传递给 DetailView。希望能帮到你。

您可以在 self.kwargs 中访问 slug。

def get_context_data(self, **kwargs):
     # Add in a QuerySet of all the books
     context = super(DetailView, self).get_context_data(**kwargs)
     slug = self.kwargs['slug']
     response = requests.get('https://api.intrinio.com/news?identifier=%s' % slug,
     ...
     )