morlandi / django-ajax-datatable

A Django app which provides the integration of a Django project with the jQuery Javascript library DataTables.net
MIT License
208 stars 64 forks source link

I want to add custom date range filter, but couldn't success #11

Closed samerda75 closed 3 years ago

samerda75 commented 3 years ago

I want to make same as below example

i am using the following code [

Screen Shot 2021-03-08 at 4 22 43 AM

](url) ajax_datatable_views.py

` class UserLogAjaxDatatableView(AjaxDatatableView): model = Change initial_order = [["date_created", "desc"], ] Rec_Count = model.objects.all().count() if Rec_Count > 500: length_menu = [[10, 25, 50, 100], [10, 25, 50, 100]] else: lengthmenu = [[10, 25, 50, 100, -1], [10, 25, 50, 100, ("All")]] search_values_separator = '+' latest_by = "date_created" show_date_filter = True

column_defs = [
    {'name': 'id', 'visible': False},
    {'name': 'date_created', 'searchable': True},
    {'name': 'user', 'foreign_field': 'user__username','visible': True, 'searchable': True},
    {'name': 'content_type', 'foreign_field': 'content_type__model','visible': True, 'searchable': True},
    {'name': 'object_repr', 'searchable': True},
    {'name': 'action', 'searchable': True},
    {'name': 'action1', 'data': None, 'visible': True, 'searchable': False, 'orderable': False, 'title':_('Action'), 'width': '50',},
]

def customize_row(self, row, obj):
    # 'row' is a dictionary representing the current row, and 'obj' is the current object.
    change_perm = '<button type="button" class="view-Log btn btn-outline-warning effect waves-light btn-xs" data-id="%s" title= "%s" ><i class="fe-eye"></i></button>'
    row['action1'] = ''

    if self.request.user.has_perm('crm.change_Log'):
        row['action1'] = \
            change_perm \
            % (reverse('crm:view_logging', args=(obj.pk,)),_("Edit"))

    return

`

list-log.html

`
$( document ).ready(function() { function hideSearchInputs(columns) { for (i=0; i<columns.length; i++) { if (columns[i]) { $('.filterhead:eq(' + i + ')' ).show(); } else { $('.filterhead:eq(' + i + ')' ).hide(); } } } AjaxDatatableViewUtils.initialize_table( $('#table_id'), "{% url 'crm:ajax_datatable_logging' %}", { // extra_options (example) processing: false, autoWidth: false, full_row_select: false, scrollX: true, colReorder: true, "pagingType": "full_numbers", responsive: true,

                dom: '<"top"<"row"<"col-md-6"l><"col-md-6">>>Prt<"bottom"<"row"<"col-md-6"i><"col-md-6"pB>>><"clear">',
                    language: {
                        buttons: {
                            "collection": "{% trans "Columns" %}",
                            "copy": "{% trans "Copy" %}",
                            "csv": "{% trans "CSV" %}",
                            "print": "{% trans "Print" %}",
                            copyTitle: '{% trans "Copy to clipboard" %}',
                            copySuccess: {
                                _: '{% trans "Copied %d rows to clipboard" %}',
                                1: '{% trans "Copied one row to clipboard" %}'
                            }
                        },
                        "sEmptyTable":     "{% trans "No data available in table" %}",
                        "sInfo":           "{% trans "Showing _START_ to _END_ of _TOTAL_ entries" %}",
                        "sInfoEmpty":      "{% trans "Showing 0 to 0 of 0 entries" %}",
                        "sInfoFiltered":   "{% trans "(filtered from _MAX_ total entries)" %}",
                        "sInfoPostFix":    "",
                        "sInfoThousands":  ",",
                        "sLengthMenu":     "{% trans "Show _MENU_ entries" %}",
                        "sLoadingRecords": "{% trans "Loading..." %}",
                        "sProcessing":     "{% trans "Processing..." %}",
                        "sSearch":         "{% trans "Search:" %}",
                        "sZeroRecords":    "{% trans "No matching records found" %}",
                        "oPaginate": {
                            "sFirst":    "{% trans "First" %}",
                            "sLast":     "{% trans "Last" %}",
                            "sNext":     "{% trans "Next" %}",
                            "sPrevious": "{% trans "Previous" %}"
                        },
                        "oAria": {
                            "sSortAscending":  "{% trans ": activate to sort column ascending" %}",
                            "sSortDescending": "{% trans ": activate to sort column descending" %}"
                        }
                    },
                    columnDefs: [
                        { responsivePriority: 1, targets: 1,},
                        { responsivePriority: 2, targets: 6,},
                    ],
                    buttons: [
                            { extend: 'collection', className: 'btn-light', buttons: [ 'columnsToggle' ]},
                            {% if perms.crm.can_copy %}
                                { extend: 'copy', className: 'btn-light'},
                            {% endif %}
                            {% if perms.crm.can_csv %}
                                { extend: 'csv', className: 'btn-light' },
                            {% endif %}
                            {% if perms.crm.can_print %}
                                { extend: 'print', className: 'btn-light' },
                            {% endif %}
                    ],
                    drawCallback: function (settings) {
                        $(".view-Log").each(function () {
                          $(this).modalForm({formURL: $(this).data('id')});
                        });
                        $('table select').selectize({
                            sortField: 'text',
                            dropdownParent: "body",
                            allowEmptyOption: false,
                        });
                      $('.dt-buttons').detach().prependTo('#controlPanel')
                      $('table input').addClass("form-control");
                },
            }, {
                // extra_data
                // ...
            },
        );
    });

`

morlandi commented 3 years ago

You shouldn't do this in the class declaration:

Rec_Count = model.objects.all().count()
if Rec_Count > 500:
    length_menu = [[10, 25, 50, 100], [10, 25, 50, 100]]
else:
    length_menu = [[10, 25, 50, 100, -1], [10, 25, 50, 100, _("All")]]

since RecCount would be evaluated only once when the file is imported. I would rather override get_length_menu as follows:

def get_length_menu(self):
    Rec_Count = model.objects.all().count()
    if Rec_Count > 500:
        length_menu = [[10, 25, 50, 100], [10, 25, 50, 100]]
    else:
        length_menu = [[10, 25, 50, 100, -1], [10, 25, 50, 100, _("All")]]
    return self.length_menu

Did you encounter other problems?

samerda75 commented 3 years ago

thank you for your reply it is useful, **But this did not solve my original point, which i would like to show the date range filter fields

can you help in this ?**

morlandi commented 3 years ago

Dear @samerda75 , I do my best to share generic advice on the usage of this library, and occasionally add some enhancements on request. However, I regret I have no time to follow specific use cases.

samerda75 commented 3 years ago

thank you for the valuable library you share, and I do understand your point in the example you include http://django-ajax-datatable-demo.brainstorm.it/tracks/ it has the same idea i am looking for if you can share the source code it will be appreciated

r1bnc commented 3 years ago

@samerda75 the code can be found here: https://github.com/morlandi/django-ajax-datatable/tree/master/example