0

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

Urls to visit: http://localhost:8000/news/SHOP/

So what my app has to do is, depending on the URL retrieve the slug and use the API of Intrinio to get a response.

The response part all works, but currently its always the same company (?identifier=SHOP). I want to make it dynamic depending on the url.

But im very new to Django and im not sure how I should pass the slug to the DetailView. I hope you can help.

Sharpless512
  • 3,062
  • 5
  • 35
  • 60

1 Answers1

7

You can access the slug in self.kwargs.

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,
     ...
     )
Alasdair
  • 298,606
  • 55
  • 578
  • 516