2

I'm trying to create link from a django-tables2 column to a 'detail view' of the object. For instance, I have a column of health providers and I want a user to be able to click on it and see specific information for the health provider from a django table of search results.

Currently, it's not working. I can get the table to show up, but cannot get it where they can click to the detail page. Please, help. There is a problem with my urls and my views, so I'm going to include the tables.py, the views.py and the urls.py. The link I'm trying to linkify is the foreign key for Hospital model in the Price Model.

This is the urls.py. This is the under url_patterns.

  path('hospital_detail/(?P<pk>\d+)/$', views.HospitalDetailView.as_view(), name='hospital-detail')

This is the views.py.

from django.template import RequestContext, get_object_or_404, render
from django.views.generic.detail import DetailView
from catalog.models import Price, Hospital, Service
from django_tables2 import RequestConfig
from catalog.tables import PriceTable

class HospitalDetailView(generic.DetailView):
    model = Hospital

def hospital_detail_view(request, primary_key):
    hop = get_object_or_404(Hospital,  pk=primary_key)
      return render(request, 'hospital_detail.html', {'hospital': hop})

def results(request):
    if request.method == "GET":
      Q=()
      out_words = request.GET.get('s')
      context = RequestContext(request)
      table = PriceTable(Price.objects.filter(service__desc_us__icontains = out_words))
      RequestConfig(request).configure(table)
    else:
      table = PriceTable(Price.objects.all())
      RequestConfig(request).configure(table)

    return render(request, 'results.html', {'table': table})

This is the tables.py. Hospital is the foreign key in the price table.

import django_tables2 as tables
from catalog.models import Service, Hospital, Price
from django_tables2.utils import A

class PriceTable(tables.Table):
    hospital = tables.LinkColumn('hospital-detail', args=[A('pk')])

    class Meta:
        model = Price
        template_name = 'django_tables2/bootstrap.html'
        sequence = ('hospital', 'service', 'price_offer', 'pub_date')
        exclude = ('id', 'published')
        attrs = {"class": "paleblue"}

1 Answers1

-1

Use tables.LinkColumn

tables.LinkColumn("hospital_detail", kwargs={"pk": tables.A("pk")}, empty_values=())
Manzurul Hoque Rumi
  • 2,911
  • 4
  • 20
  • 43
  • I didn't down vote this, but this does not work. It does not create a hyperlink to the detail view for the heatlh providers. I get the following error - "No Reverse Match - "hospital-detial" not found. –  Feb 12 '19 at 23:12
  • 1
    Use Django `reverse()` https://docs.djangoproject.com/en/2.1/ref/urlresolvers/#reverse – Manzurul Hoque Rumi Feb 13 '19 at 04:18