在DetailView

时间:2017-05-19 15:11:40

标签: python django python-3.x django-1.11

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)。我想根据网址使其动态化。

但是我对Django非常新,我不确定如何将slug传递给DetailView。我希望你能提供帮助。

1 个答案:

答案 0 :(得分:3)

您可以访问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, ... ) 中的slug。

{{1}}