Giter Club home page Giter Club logo

django-datatable-view's Introduction

Datatable View

This package is used in conjunction with the jQuery plugin DataTables, and supports state-saving detection with fnSetFilteringDelay. The package consists of a class-based view, and a small collection of utilities for rendering table data from models.

PyPI Downloads PyPI Version Build Status Documentation Status

Dependencies:

Getting Started

Install the package:

pip install django-datatable-view

Add to INSTALLED_APPS (so default templates and js can be discovered), and use the DatatableView like a Django ListView:

# settings.py
INSTALLED_APPS = [
    'datatableview',
    # ...
]


# views.py
from datatableview.views import DatatableView
class ZeroConfigurationDatatableView(DatatableView):
    model = MyModel

Use the {{ datatable }} provided in the template context to render the table and initialize from server ajax:

<!-- myapp/mymodel_list.html -->

<!-- Load dependencies -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<!-- Load js for initializing tables via their server-side options -->
<script type="text/javascript" charset="utf8" src="{% static 'js/datatableview.js' %}"></script>
<script type="text/javascript">
    $(function(){
        datatableview.initialize($('.datatable'));
    });
</script>

<!-- Render the table skeleton, includes the .datatable class for the on-ready initializer. -->
{{ datatable }}

Features at a glance

  • DatatableView, a drop-in replacement for ListView that allows options to be specified for the datatable that will be rendered on the page.
  • MultipleDatatableView for configurating multiple Datatable specifications on a single view
  • ModelForm-like declarative table design.
  • Support for ValuesQuerySet execution mode instead of object instances
  • Queryset caching between requests
  • Customizable table headers
  • Compound columns (columns representing more than one model field)
  • Columns backed by methods or callbacks instead of model fields
  • Easy related fields
  • Automatic search and sort support
  • Total control over cell contents (HTML, processing of raw values)
  • Search data fields that aren't present on the table
  • Support for DT_RowData
  • Customization hook for full JSON response object
  • Drop-in x-editable support, per-column
  • Customizable table templates
  • Easy Bootstrap integration
  • Allows all normal dataTables.js and x-editable Javascript options
  • Small library of common column markup processors
  • Full test suite

Documentation and Live Demos

Read the module documentation at http://django-datatable-view.readthedocs.org.

A public live demo server is in the works. For version 0.8, we will continue to keep the live demo site alive at http://django-datatable-view.appspot.com/ Please note that 0.8 does not reflect the current state or direction of the project.

You can run the live demos locally from the included example project, using a few common setup steps.

$ git clone https://github.com/pivotal-energy-solutions/django-datatable-view.git
$ cd django-datatable-view
$ mkvirtualenv datatableview
(datatableview)$ pip install -r requirements.txt
(datatableview)$ datatableview/tests/example_project/manage.py migrate
(datatableview)$ datatableview/tests/example_project/manage.py loaddata initial_data
(datatableview)$ datatableview/tests/example_project/manage.py runserver

The example project is configured to use a local sqlite3 database, and relies on the django-datatable-view app itself, which is made available in the python path by simply running the project from the distributed directory root.

Authors

  • Autumn Valenta
  • Steven Klass

Copyright and license

Copyright 2011-2023 Pivotal Energy Solutions. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at:

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

django-datatable-view's People

Contributors

akx avatar alshar avatar arti3dplayer avatar charn avatar chornsby avatar danmac-uk avatar doganmeh avatar ekohl avatar forever-young avatar fritz-k avatar greenbender avatar hiroki-sawano avatar humphrey avatar jacobvalenta avatar jangeador avatar jayala avatar jherskovic avatar jiding-qd avatar johnrtipton avatar michaeldjeffrey avatar predatell avatar rcorzogutierrez avatar rh0dium avatar robintema avatar tiliv avatar tomyam1-personal avatar zopieux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-datatable-view's Issues

Helper callbacks (improvements and ideas)

If you have suggestions for column helper functions that you find valuable (both as an in-method utility, or as a direct column callback), please comment here or open other issues with ideas.

Ideally, I'd like to see a one-liner example of how you'd like to be able to interact with the helper, even if you don't know how exactly it would work. This helps demonstrate what you would like to accomplish, and makes it easier to understand

For example, if you were pitching the built-in format_date() helper, something like this would be helpful in your comment:

["Description", 'description', helpers.format_date("%Y-%m-%d")]

Happy datatabling ;)

  • x-editable helper ( #16 )
  • through_filter — wrapper around other naive callables, like Django's default filters

Return errors if errors are found.

Hi there,

Somehow we need to alert developers when a query set is not bringing back good data. Either we need to dump it to logger or return something back to the table. I don't like the later b/c we don't want this getting to the end user..

Local Storage - Ensuring the last query was a success.

I have seen a case where the data in local storage causes the page to not render as the stored options (or something) are so jacked up that the page never renders. It would be handy to update the stored options after the last fetched returned results come indicating it was a success. Then before you use the options you check to make sure that the last use of it was a success or you nuke the results.

Need a "clean" way to add field types.

Hi there,

I'm using django-netfields in my app and I while trying to display a table with netfields elements I ran into this:

ValueError: Unhandled field type for address (<class 'netfields.fields.InetAddressField'>) in search.

So, I looked in the code and so far, the only way I found was to override the "quite big" apply_queryset_options in the DatatableMixin class.

Could it be possible to have a more user friendly way to add more supported types ? Perhaps making this "if options['search']:" a separate function definition that could be used with super().

Any ideas?

helpers.format makes sorting work as if column is text rather than numeric

I am using the helpers.format function to return numbers with commas included, helpers.format("{0:,}") to be specific, but I'm having an issue because if I click the column to sort the results they are getting returned as if the column were a text (non-numeric) field. Below is the order that the results are getting returned. Here is a screenshot of the table results.

  • 7,786
  • 52
  • 5,406
  • 43
  • 4,692
  • 4
  • 318
  • 2,857
  • 158
  • 1,676

What can I do to have them be returned in the correct order (7,786 > 5,406 > 4692, and so on)?

My development environment is the following:

  • Django 1.6.5
  • Python 2.7.5
  • django-datatable-view 0.7.1

Consider respecting ListView paging options

The Django MultipleObjectMixin uses a class attribute paginate_by to define page size.

Using the pagination class and paginate_queryset() paradigms would also be interesting, but we'll have to figure out if that's reasonable, given how we don't actually paginate querysets, but object lists.

get_datatable_options load multiple time

running v0.7 the get_datatable_options runs multiple times, I use this method to add columns in a view but everytime the page is loaded adds the column again. I debug and the protection for that doesn't works well, even i am reloading the same view the hasatrr return false.

Some kind of default column hide/show template tag

I have no idea how this would/whether this should be implemented but thought I would throw it in the ideas pile.

At the moment I use http://bootstrap-switch.org/ to create a really nice show/hide column filter. Basically I include a template above my table that looks something like this:

<div class="column-switch">
    <div class="switch-label">Column 1</div>
    <div id="column-1-switch" class="make-switch switch-small" data-on="success"
         data-off="warning"
         data-on-label="<i class='icon-ok icon-white'></i>"
         data-off-label="<i class='icon-remove'></i>">
        <input type="checkbox" class="toggle" value="column-1"/>
    </div>
</div>
<div class="column-switch">
    <div class="switch-label">Column 2</div>
    <div id="column-2-switch" class="make-switch switch-small" data-on="success"
         data-off="warning"
         data-on-label="<i class='icon-ok icon-white'></i>"
         data-off-label="<i class='icon-remove'></i>">
        <input type="checkbox" class="toggle" value="column-2"/>
    </div>
</div>

etc, etc

Then I have in my js:

$('#column-1-switch').on('switch-change',function (e, data) {
    var value = data.value;
    changeColumnVisibility(0, value);
}).bootstrapSwitch('setState', true);

$('#column-2-switch').on('switch-change',function (e, data) {
    var value = data.value;
    changeColumnVisibility(1, value);
}).bootstrapSwitch('setState', true);

Which basically lets the user turn on/off the visibility of the column. I guess something along these lines as an optional templatetag would be handy i.e. {% datatableview_columnvisibility %}

x-editable helper

You mentioned in #15 ideas for helpers. Well im pretty sure I could come up with a bunch of ideas based on what im already hacking together myself. This one is really helpful though.

I am using x-editable https://github.com/vitalets/x-editable. I have created a really simple but stupid way of returning x-editable compatible fields:

def make_xeditable(data, data_id, data_type, data_pk, data_url, data_title, data_value):
    rich_data = """<a href="#" id="{}" data-type="{}" data-pk="{}" data-url="{}" data-title="{}" data-value="{}" data-placeholder="{}">{}</a>""".format(
        data_id, data_type, data_pk, data_url, data_title, data_value, data_title, data)
    return rich_data

Works great but it means passing in the data yourself:

def get_column_driver_data(self, instance, *args, **kwargs):
        driver = instance.driver
        rich_data = make_xeditable(driver, 'driver', 'select2', instance.id, reverse('update-url'), trans("Enter Driver"),
                                   driver)
        return rich_data

It also requires then adding in the x-editable js implementation yourself also.

    $.fn.editable.defaults.mode = 'inline';
    $('td a#driver', dTable.fnGetNodes()).editable({
        select2: {
            ajax: {
                url: Django.url('drivers-list'),
                dataType: 'json',
                data: function (term, page) {
                    return { query: term };
                },
                results: function (data, page) {
                    return { results: data.results };
                }
            }
        },
        success: function (response, newValue) {
            if (response.status == 'error') return response.msg;
        }
    });

Would be lovely to be able to get this all done via datatable-view to have fully editable tables!!

Django 1.7 changes model registration, breaks test_app.models hack

Sort of a trainwreck, hinging on the fact that the models dictionary in Django 1.7's internals is no longer finding our patched-in test models. It looks like the models dictionary needs some kind of a refresh after the INSTALLED_APPS hack, before the syncdb (?)

Traceback (most recent call last):
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/apps/config.py", line 152, in get_model
    return self.models[model_name.lower()]
KeyError: 'relatedmodel'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/python.py", line 156, in _get_model
    return apps.get_model(model_identifier)
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/apps/registry.py", line 190, in get_model
    return self.get_app_config(app_label).get_model(model_name.lower())
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/apps/config.py", line 155, in get_model
    "App '%s' doesn't have a '%s' model." % (self.label, model_name))
LookupError: App 'test_app' doesn't have a 'relatedmodel' model.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/json.py", line 75, in Deserializer
    for obj in PythonDeserializer(objects, **options):
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/python.py", line 93, in Deserializer
    Model = _get_model(d["model"])
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/python.py", line 158, in _get_model
    raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
django.core.serializers.base.DeserializationError: Invalid model identifier: 'test_app.RelatedModel'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/test/testcases.py", line 182, in __call__
    self._pre_setup()
  File "./datatableview/tests/testcase.py", line 18, in _pre_setup
    super(DatatableViewTestCase, self)._pre_setup()
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/test/testcases.py", line 754, in _pre_setup
    self._fixture_setup()
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/test/testcases.py", line 907, in _fixture_setup
    'skip_checks': True,
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/management/__init__.py", line 115, in call_command
    return klass.execute(*args, **defaults)
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/management/base.py", line 337, in execute
    output = self.handle(*args, **options)
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/management/commands/loaddata.py", line 60, in handle
    self.loaddata(fixture_labels)
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/management/commands/loaddata.py", line 90, in loaddata
    self.load_label(fixture_label)
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/management/commands/loaddata.py", line 141, in load_label
    for obj in objects:
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/json.py", line 81, in Deserializer
    six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2])
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/utils/six.py", line 549, in reraise
    raise value.with_traceback(tb)
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/json.py", line 75, in Deserializer
    for obj in PythonDeserializer(objects, **options):
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/python.py", line 93, in Deserializer
    Model = _get_model(d["model"])
  File "/Users/Kaori/.virtualenvs/dtv3/lib/python3.4/site-packages/django/core/serializers/python.py", line 158, in _get_model
    raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/Kaori/Projects/Pivotal/django-datatable-view/datatableview/tests/test_app/fixtures/test_data.json': Invalid model identifier: 'test_app.RelatedModel'

Filter object_list later in serialize_to_json for easy calculation of whole dataset

First tnx for this great django binding! I integrated it and wanted something similar as her: http://datatables.net/examples/advanced_init/footer_callback.html. As soon I edited it for my needs I realized, that the view (of course) paginates the data sending to the table, so that no calculation on the WHOLE dataset is possible in the client in js.
So I googled again and came up, with the possibility of giving custom server side data to the table: http://stackoverflow.com/questions/6090260/jquery-datatables-return-additional-information-from-server (should be faster anyway)

So I came up with the following solution (sorry for not making a diff - first post her on github):

removing the last lines in apply_queryset_options and moving them to

def serialize_to_json(self, object_list):

      [...]

        object_list, total_records, unpaged_total = object_list

        options = self._get_datatable_options()

        # Do some things here with your FULL object list
        debit_rental = 0
        credit_rental = 0
        sum_rental = 0

        for obj in object_list:
            if obj.debit:
                debit_rental += obj.rental
            else:
                credit_rental += obj.rental
        sum_rental = credit_rental - debit_rental

        full_response = {'sum_rental' : '{0:.2f}'.format(sum_rental),
                        }
       # Filter here not in apply_queryset_options
        if options.page_length != -1:
            i_begin = options.start_offset
            i_end = options.start_offset + options.page_length
            object_list = object_list[i_begin:i_end]

        # Do something with filtered object_list if needed

        response_obj = {
            'sEcho': self.request.GET.get('sEcho', None),
            'iTotalRecords': total_records,
            'iTotalDisplayRecords': unpaged_total,
            'aaData': [self.get_record_data(obj) for obj in object_list],
        }

        #Add Dict to response
        response_obj.update(full_response)

        return json.dumps(response_obj, indent=4)

With this edit it would be easy to do so with just overwriting serialize_to_json.

Probmel with column visible and column bVisible settings

I'am using datatables 1.9.4, jquery 2.0.3.

I have problem with bVisible variable in columns settings:
I'am using this template for render table:

 <table class="datatable table table-condensed" data-url="{{ datatable.url }}" data-result-counter-id="{{ result_counter_id }}" id="type_of_work_list_table">
        <thead>
            <tr>
                {% for name, attributes in datatable %}
                    <th data-name="{{ name|slugify }}" {{ attributes }}>{{ name }}</th>
                {% endfor %}
            </tr>
        </thead>
 </table>

And this settings for view:

class DepartmentListView(DatatableView):
    model = Department
    template_name = "departments_list.html"
    datatable_options = {
        'columns': [
            (u"dep", 'title'),
            ""
        ],
    }

And it's result in table with header, containing in tbody and no data (td) in rows.
Why?
I'am output column options in django-datatables-view.js, and bVisible variable in it always false..

Object {undefined: "dep", bSortable: false, bVisible: false}
Object {undefined: "", bSortable: false, bVisible: false} 

Table data row onclick redirect to new page

Although the previous issue has been closed, but don't think it answered my question in the documentation.
I don't want the inline editing, but a click on the row, to redirect to another page or op up the new page.

Kind regards

Example m2m page does not work

I am eager to use django-datatable-view to generate tables out of my models. I am successful in playing with it excepted when I need to add a column related to a m2m relationship. Your example and my own setup does not handle it well.

http://django-datatable-view.appspot.com/many-to-many-fields/

The models (pseudo Python):

class UpscalingTask:
keyword_set = m2m to Keyword

class Keyword:
label = string field

The columns in configuration:

    datatable_options = {
        'structure_template': 'upscaling/task/table_structure.html',
        'columns': [
            ('Keywords', 'keyword_set', 'get_keywords_data')
        ]
    }

My various other trial and error:

1. ('Keywords', 'keyword_set__all', 'get_keywords_data')
2. ('Keywords', 'keyword_set__all__label', 'get_keywords_data')
3. ('Keywords', 'keyword_set__label', 'get_keywords_data')

The error on my own setup:

ERROR Internal Server Error: /fr/upscaling/task/table
Traceback (most recent call last):
  File "/home/ubuntu/cloudncode/venv/src/django/django/core/handlers/base.py", line 111, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/ubuntu/cloudncode/venv/src/django/django/views/generic/base.py", line 69, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/ubuntu/cloudncode/venv/src/django-braces/braces/views/_access.py", line 66, in dispatch
    request, *args, **kwargs)
  File "/home/ubuntu/cloudncode/server/cloudncode_base/views/mixins.py", line 84, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/home/ubuntu/cloudncode/venv/src/django/django/views/generic/base.py", line 87, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 59, in get
    return self.get_ajax(request, *args, **kwargs)
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 304, in get_ajax
    response_data = self.get_json_response_object(object_list, total, filtered_total)
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 328, in get_json_response_object
    'aaData': [self.get_record_data(obj) for obj in object_list_page],
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 328, in <listcomp>
    'aaData': [self.get_record_data(obj) for obj in object_list_page],
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 373, in get_record_data
    column_data = self.get_column_data(i, name, obj)[0]
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 386, in get_column_data
    kwargs['default_value'] = self._get_column_data_default(instance, column)[1]
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 504, in _get_column_data_default
    value = reduce(chain_lookup, [instance] + field_name.split('__'))
  File "/home/ubuntu/cloudncode/venv/src/django-datatable-view/datatableview/views.py", line 499, in chain_lookup
    value = value()
  File "/home/ubuntu/cloudncode/venv/src/django/django/db/models/fields/related.py", line 837, in __call__
    manager = getattr(self.model, kwargs.pop('manager'))
KeyError: 'manager'

Table clickable or Row selected

How can I make it clickable on data, and redirect to another page.
For example. click on the customer id --> redirect to new page to edit the customer details

hidden_columns aren't rendered

Here is my (shortend) dict:

datatable_options = {
        'columns': [
            ('action', None, 'get_pay_link'),
        ],
        'unsortable_columns': [
            'text',
        ],
        'hidden_columns': [
            'get_test', #function
            'modelfield', 
        ],
}

hidden_columns will not render in my templates (I expected hidden td fields). No changes in default_structure.html. Tested with 0.5.4

all the input of the page filter the datatable

I have a page with an input in the side menu, when in the content i load a datatable, the input of the sidemenu search the datatable, it is not near in the html to the datatable. I remove the script for initialization and this strange behavior stop and works as usual.

Issues with the "format_date" helper - With fix

For some reason, my DateTimeField (even with null=True) cannot be parsed by the format_date helper when empty:

[...]
    value = localtime(value)
  File "/home/noss/.virtualenvs/noss/lib/python2.7/site-packages/django/utils/timezone.py", line 261, in localtime
    value = value.astimezone(timezone)
AttributeError: 'unicode' object has no attribute 'astimezone'

My fix is to catch empty unicode strings as well as None:

def format_date(format_string, localize=False, key=None):
    if localize is not False and localtime is None:
        raise Exception("Cannot use format_date argument 'localize' with Django < 1.5")
    def helper(value, *args, **kwargs):
        if key:
            value = key(value)
        else:
            value = kwargs.get('default_value', value)
        if value is None or value == u'':
            return ""
        if localize:
            value = localtime(value)
        return value.strftime(format_string)

    if key:
        return keyed_helper(helper)(key=key)
    return helper

DatatableStructure object has no attribute code

Simply use {{ datatable }} with Django 1.7+ Python 3.4 and you will get a nice error.

I guess that someone copy-pasted the class StrAndUnicode in utils.py from the project django_countries without actually testing it.

try:
    from django.utils.encoding import StrAndUnicode
except ImportError:
    from django.utils.encoding import python_2_unicode_compatible

    @python_2_unicode_compatible
    class StrAndUnicode:
        def __str__(self):
            return self.code

helpers.format_date does not render the date in template

Just a small thing, but in my case helpers.format_date seems broken. The field is empty ('') after the rendering

datatable_options = {
        'columns': [
            ('action', None, 'get_pay_link'),
            #('date booking for', 'date_for' , helpers.format_date('%d.%m.%Y')), # Todo helper does't work
            ('date booking for', 'date_for', helpers.attrgetter('get_date_for_localized')),
            ]
}

Documents for how to write templete?

view.py
class SampleDataTableView(DatatableView):
model = Group
datatable_options = {
'columns': [
'id',
'name',
]
}

"datatableview.initialize($('.mytable'));"
But Just place above line in templete give no records like this.
result

Filter on table data at VIew

When I defined in Django view:

model = example-Model

How can I filter the table data I want to show, I cannot do example-Model.objects.filter(id=""), because it is not an Object.

How can I do filters?
Thanks

td class = field name

In the same way that you add field name as the class for 'th' in the header it would be helpful for customising if each 'td' also had the field name as a class. I do it at the moment via confirm_datatable_options and aoColumnDefs but it sure would be nicer if it came for free :)

options.aoColumnDefs = [
        { "sClass": "field_name_0", "aTargets": [ 0 ] },
        { "sClass": "field_name_1", "aTargets": [ 1 ] },
        { "sClass": "field_name_2", "aTargets": [ 2 ] },
        { "sClass": "field_name_3", "aTargets": [ 3 ] },
etc
    ];

Prevent get_context_data from putting the queryset into the context

The default simplest case lets the use ignore the standard object_list. Let's remove it by default, so that an expensive get_queryset() method isn't unduly taxing performance.

The original plan was that a queryset, being lazy, won't create any queries, but if the user has a complicated queryset lookup, the initial page load performance is damaged without any obvious reason. The only defense as a user against this is to return queryset.none() if self.request.is_ajax() == True. That's something the user shouldn't have to think about.

Missing files

I have tried installing the package using pip and by downloading the tarball. In either case the install is not complete per the following:

aklaver@killi:~/test/django-datatable-view-0.5.1> python setup.py build
running build
running build_py
running egg_info
writing django_datatable_view.egg-info/PKG-INFO
writing top-level names to django_datatable_view.egg-info/top_level.txt
writing dependency_links to django_datatable_view.egg-info/dependency_links.txt
reading manifest file 'django_datatable_view.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'static/js/.js'
warning: no files found matching 'templates/datatableview/
.html'
writing manifest file 'django_datatable_view.egg-info/SOURCES.txt'

Setting the "oLanguage" datatable option is not completely respected

Setting something like this:

<script type="text/javascript">
    datatableview.auto_initialize = false;
    var options = {
        "oLanguage": {
            "sUrl": "{{STATIC_URL}}/js/datatables/language.{{ LANGUAGE_CODE }}.json"
        }
    };
    datatableview.initialize($('.datatable'), options);
</script>

...gets some of the strings translated but not all of them, i.e.: "Showing nnn to nnn of nnnn entries" stays the same.

The same option with the same oLanguage setting works flawlessly on a normally initialized datatable.

Any ideas why ?

Bootstrap theme

I have tried adding a theme and can not
Is there any way to add the theme "Twitter Bootstrap"?
thank

Add a next param to link_to_model

Similar to this:

@keyed_helper
def link_to_model(instance, text=None, next=None, *args, **kwargs):
    """
    Returns HTML in the form

        <a href="{{ instance.get_absolute_url }}">{{ instance }}</a>

    If ``text`` is provided and is true-like, it will be used as the hyperlinked text.

    If ``next`` is provided, it will be passed as the next parameter.

    Else, if ``kwargs['default_value']`` is available, it will be consulted.

    Failing those checks, ``unicode(instance)`` will be inserted as the hyperlinked text.

    """
    if not text:
        text = kwargs.get('default_value') or unicode(instance)
    if next:
    return u"""<a href="{}?next={}">{}</a>""".format(instance.get_absolute_url(), next, text)
    else:
    return u"""<a href="{}">{}</a>""".format(instance.get_absolute_url(), text)

Bug with python 2.6 - empty format placeholders

First of all kudos for django-datatable-view, i find it really helpful !

Now, I have found a bug when I tried to use it with python 2.6. In the file datatableview/helpers.py, line 86 there is the following code

return u"""<a href="{}">{}</a>""".format(instance.get_absolute_url(), text)

However, empty placeholders for format are not allowed in python 2.6 (it throws a ValueError: zero length field name in format, also check the answer to this SO question http://stackoverflow.com/questions/10054122/valueerror-zero-length-field-name-in-format-python) - in 2.7 it is working fine.

I was able to fix it by changing the above line to:

return u"""<a href="{0}">{1}</a>""".format(instance.get_absolute_url(), text)

I'd really appreciate it if you apply the fix and put the new version in your pip repository.

Best regards,
Serafeim

pypi integration?

Any chance of adding pypi integration to enable a simple "pip install django-datatable-view"?

Add a fully functional example Django project

Showcasing how to do everything is much more effective than a massive README full of options. An example project would demonstrate very quickly what is possible and what is not.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.