nixnotwin
nixnotwin

Reputation: 2403

Django tables 2: Hyperlinking items in a column

My app displays a table with many columns. I use Django tables 2 app to render the table. I am trying to make items in one column hyperlinked so that users can click. The url pattern is simple: /contact/pk/, for e.g. /contact/2/. This is what I have in my models:

#models.py

class Contact(models.Model):
    name = models.CharField(max_length=200)
    . . .

class ContactTable(tables.Table):

    name = tables.LinkColumn('contact_detail', args=[A('pk')])
    class Meta:
        model = Contact
        attrs = {"class": "paleblue"}

#urls.py

url(r'^contact/(?P<item_id>\d+)/$', 'app.views.contact_view', name='contact_detail'),

However, the items do not get hyperlinked.

Upvotes: 3

Views: 7136

Answers (3)

Joel Aufrecht
Joel Aufrecht

Reputation: 463

nixnotwin's solution uses hard-coded URLs. To use reverse lookup urls:

class ContactTable(tables.Table):
    edit_entries = tables.TemplateColumn('<a href="{% url \'contact_detail\' record.id %}">Edit</a>')

Upvotes: 5

Adam Taylor
Adam Taylor

Reputation: 4839

What are you passing to render_table in your template? Just a regular QuerySet? My guess is you forgot to instantiate and configure the table in your view. Here is the example provided in the docs:

# tutorial/views.py
from django.shortcuts import render
from django_tables2   import RequestConfig
from tutorial.models  import Person
from tutorial.tables  import PersonTable

def people(request):
    table = PersonTable(Person.objects.all())
    RequestConfig(request).configure(table)
    return render(request, 'people.html', {'table': table})

If you do it like this, it should work fine.

UPDATE:

I know that the problem has already been resolved, but I noticed that the name = tables.LinkColumn('contact_detail', args=[A('pk')]) line of code is within the ContactTable class's inner Meta class. It should be outside of the inner Meta class.

Upvotes: 0

nixnotwin
nixnotwin

Reputation: 2403

This solved it:

class ContactTable(tables.Table):
    edit_entries = tables.TemplateColumn('<a href="/contact/{{record.id}}">Edit</a>')

    class Meta:
        model = Contact
        attrs = {"class": "paleblue"}

Upvotes: 13

Related Questions