Is there a way to auto populate column header on template rather than hard coding?

Issue #40 closed
Former user created an issue

Hi Team,

Thank you for the wonderful package.

I wanted to know is there a way where in which i can use column names auto populated instead of hard coding like below.

<table class="datatable">
        <thead>
            <th>{% trans "Username" %}</th>
            <th>{% trans "E-mail" %}</th>
        </thead>
        <tbody>
        </tbody>
    </table>

Is it possible to use the columns which is specified on the view to be able to use on teh template?

some thing like below, I am hoping this will also maintain the order in which the data is being pulled from the db.

<table class="datatable">
        <thead>
             {% for col in view.columns %}
            <th>{% trans col %}</th>
            {% end for %}
        </thead>
        <tbody>
        </tbody>
    </table>

Comments (3)

  1. Maciej Wisniowski repo owner

    There is one view that renders the table itself and second one (django-datatables-view) that handles data preparation for the table. This means django-datatabbles-view is all about data retrieval, not table rendering and there is no built-in way to do what you want. You have to handle it by yourself - you can inherit from base classes and do what you need.

  2. just10minutes

    Thank you for your response. I understand what you mean.

    Now in order to tackle this I copy and paste the columns variable in my templateView as well, so now i can access the column headers using view.columns tag on my templates

    class UsersList110(TemplateView):
        template_name = 'ddv_example/users_list_1_10.html'
        columns = ['username', 'email']   #This should be same declaration as below view so I can access this on my template like [% for column in view.columns %}
    
    
    class UsersList110Json(BaseDatatableView):
        model = User
        columns = ['username', 'email']
        order_columns = ['username', 'email']
    

    I am not sure of any adverse impact of this as of now, I hope there shouldn't be any.

    Thank you

  3. Maciej Wisniowski repo owner

    In 1.17.0 it is possible to not define columns on the view level - these will be read from the request sent by datatables if only there is a proper columns definition (name attribute has to be filled for each column),eg:

    columnDefs: [
                        {
                            name: 'username',
                            targets: [0]
                        },
                        {
                            name: 'email',
                            targets: [1]
                        }
                    ]
    
  4. Log in to comment