Django-tables2: Change text displayed in column title

你。 提交于 2019-12-09 03:32:36

问题


I am working with a MySQL view (Create View as Select ...) and have successfully manged to connect the view to a model like this:

#models.py
class Dashboard(models.Model):
    devenv = models.CharField(max_length=30, primary_key=True)
    numberofissues = models.BigIntegerField()
    class Meta:
        managed=False
        db_table = 'stability_dashboard'

I have also managed to display data in a table using the boiler plate code from the example:

#tables.py
class DashboardTable(tables.Table):
    class Meta:
        model = Dashboard
        attrs = {'class': 'paleblue'}

#views.py
def dashboard(request):
    table = DashboardTable(Dashboard.objects.all())
    RequestConfig(request).configure(table)
    return render(request, 'uptime/dash.html', {'table': table})

I would now like to change the title displayed in each column to something more understandable including spaces e.g. Instead of 'devenv' => 'Development Environment'


回答1:


Just add the columns whose names you want to override in your tables.py. For instance

#tables.py
import django_tables2 as tables
from models import Dashboard

class DashboardTable(tables.Table):
  devenv = tables.Column(verbose_name= 'Development Environment' )

  class Meta:
    model = Dashboard
    attrs = {'class': 'paleblue'}

Another (probably more DRY) solution is to leave tables.py as is and add verbose_name in your model definition:

#models.py
class Dashboard(models.Model):
    devenv = models.CharField(max_length=30, primary_key=True, verbose_name='Development Environment')
    numberofissues = models.BigIntegerField(verbose_name='Number of Issues')
    class Meta:
        managed=False
        db_table = 'stability_dashboard'


来源:https://stackoverflow.com/questions/15601300/django-tables2-change-text-displayed-in-column-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!