Exemplo n.º 1
0
    def test_has_link(self):
        foreign_1 = ForeignModelWithUrl.objects.create(title='foreign test')
        foreign_2 = ForeignModelWithoutUrl.objects.create(title='foreign test')
        SampleModel.objects.create(title='test',
                                   category="blog_post",
                                   foreign_1=foreign_1,
                                   foreign_2=foreign_2)
        SampleModel.objects.create(title='test',
                                   category="blog_post",
                                   foreign_1=None,
                                   foreign_2=None)

        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', 'foreign_1',
                                             'foreign_2'))
        # test if link exists
        test_1_item = smart_list.items[-2]
        self.assertTrue(test_1_item.fields()[0].has_link())
        self.assertEqual('/admin/testproject/samplemodel/2/change/',
                         test_1_item.fields()[0].get_absolute_url())
        self.assertTrue(test_1_item.fields()[1].has_link())
        self.assertEqual('/admin/testproject/foreignmodelwithurl/1/change/',
                         test_1_item.fields()[1].get_absolute_url())
        self.assertFalse(test_1_item.fields()[2].has_link())

        # test there is no link on None
        test_2_item = smart_list.items[-1]
        self.assertFalse(test_2_item.fields()[1].has_link())
Exemplo n.º 2
0
 def test_get_column_from_method(self):
     smart_list = SmartList(SampleModel.objects.all(),
                            **{'list_display': ('some_display_method', )})
     self.assertEqual('Some Display Method',
                      smart_list.columns[0].get_title())
     self.assertEqual('I just love django-smart-lists! blog_post',
                      smart_list.items[0].fields()[0].get_value())
Exemplo n.º 3
0
    def test_custom_filter_classes_parsing(self):
        class BlogOrNotFilter(SmartListFilter):
            parameter_name = 'blog'
            title = 'BlogOrNot'

            def lookups(self):
                return (
                    ('blog', 'Blog'),
                    ('orNot', 'OR NOT!'),
                )

            def queryset(self, queryset):
                if self.value() == 'blog':
                    return queryset.filter(category="blog_post")
                if self.value() == 'blog':
                    return queryset.exclude(category="blog_post")
                return queryset

        request = self.factory.get('/smart-lists/')
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', 'category'),
                               list_filter=(BlogOrNotFilter(request),
                                            'category'))

        # print(smart_list.filters)
        fltr = smart_list.filters[0]
        self.assertEqual(fltr.get_title(), 'BlogOrNot')

        values = fltr.get_values()
        self.assertEqual(values[0].get_title(), 'All')
        self.assertEqual(values[0].is_active(), True)
        self.assertEqual(values[1].get_title(), 'Blog')
        self.assertEqual(values[1].is_active(), False)
        self.assertEqual(values[2].get_title(), 'OR NOT!')
        self.assertEqual(values[2].is_active(), False)

        request = self.factory.get('/smart-lists/?blog=blog')
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', 'category'),
                               list_filter=(BlogOrNotFilter(request), ),
                               query_params=request.GET)

        fltr = smart_list.filters[0]
        values = fltr.get_values()
        self.assertEqual(values[0].is_active(), False)
        self.assertEqual(values[1].is_active(), True)
        self.assertEqual(values[2].is_active(), False)
Exemplo n.º 4
0
    def test_queryset_returning_dict(self):
        qs = SampleModel.objects.all().annotate(custom=F('category')).values(
            'custom', 'title')
        smart_list = SmartList(qs, list_display=('title', 'category'))

        self.assertEqual(
            'I just love django-smart-lists!',
            smart_list.items[0].fields()[0].get_value(),
        )
Exemplo n.º 5
0
    def test_labels_for_columns(self):
        """Test if labels works properly."""
        label = 'Custom column label'
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', ('category', label)))

        column_with_custom_label = smart_list.columns[-1]

        self.assertEqual(label, column_with_custom_label.label)
        self.assertEqual(label, column_with_custom_label.get_title())
Exemplo n.º 6
0
def smart_list(context, object_list=None, page_obj=None, is_paginated=None, paginator=None, query_params=None,
               list_display=None, list_filter=None, list_search=None, search_query_param=None,
               ordering_query_param=None, grid_size=12, table_class='table-striped', table_link_class='font-weight-bold'):
    """
    Display the headers and data list together.

    TODO: Do pagination inside here??
    """
    if not object_list:
        object_list = context['object_list']
    if not page_obj:
        page_obj = context.get('page_obj', None)
    if not is_paginated:
        is_paginated = context.get('is_paginated')
    if not paginator:
        paginator = context.get('paginator')

    if query_params is None:  # required
        query_params = context['smart_list_settings']['query_params']
    if list_display is None:  # required
        list_display = context['smart_list_settings']['list_display']
    if list_filter is None:  # optional
        list_filter = context.get('smart_list_settings', {}).get('list_filter', [])
    if list_search is None:
        list_search = context.get('smart_list_settings', {}).get('list_search', [])
    if search_query_param is None:
        search_query_param = context.get('smart_list_settings', {}).get('search_query_param', 'q')
    if ordering_query_param is None:
        ordering_query_param = context.get('smart_list_settings', {}).get('ordering_query_param', 'o')

    smart_list_instance = SmartList(
        object_list,
        query_params=query_params,
        list_display=list_display,
        list_filter=list_filter,
        list_search=list_search,
        search_query_param=search_query_param,
        ordering_query_param=ordering_query_param
    )

    split_grid_small_size = int(round(grid_size * 0.25))
    return {
        'smart_list': smart_list_instance,
        'page_obj': page_obj,
        'is_paginated': is_paginated,
        'paginator': paginator,
        'full_width_grid': grid_size,
        'split_grid_large': grid_size - split_grid_small_size,
        'split_grid_small': split_grid_small_size,
        'table_class': table_class,
        'table_link_class': table_link_class
    }
Exemplo n.º 7
0
 def test_new_filter_clears_pagination(self):
     request = self.factory.get(
         '/smart-lists/?page=2&o=1&category=blog_post')
     smart_list = SmartList(
         SampleModel.objects.all(),
         list_display=('title', 'category'),
         list_filter=('title', 'category'),
         query_params=request.GET,
     )
     fltr = smart_list.filters[0]
     url = fltr.get_values()[0].get_url()
     self.assertEqual(set(url[1:].split('&')),
                      set(['o=1', 'category=blog_post']))
Exemplo n.º 8
0
    def test_custom_html_column(self):
        """Test custom html column works properly."""
        render_column_function = lambda obj: SafeText(
            '<b>Custom column redered</b>')
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', (render_column_function,
                                                       'Column label')))

        smart_list_item_field_with_custom_render = smart_list.items[-1].fields(
        )[-1].get_value()

        self.assertEqual(render_column_function(SampleModel.objects.last()),
                         smart_list_item_field_with_custom_render)
Exemplo n.º 9
0
    def test_ordering_of_columns(self):
        smart_list = SmartList(
            SampleModel.objects.all(), **{
                'list_display': ('title', 'category', 'some_display_method',
                                 'friendly_category')
            })

        self.assertEqual(smart_list.columns[0].order_field, 'title')
        self.assertEqual(smart_list.columns[0].order.column_id, 1)
        self.assertEqual(smart_list.columns[1].order_field, 'category')
        self.assertEqual(smart_list.columns[1].order.column_id, 2)
        self.assertEqual(smart_list.columns[2].order_field, None)
        self.assertEqual(smart_list.columns[2].order, None)
        self.assertEqual(smart_list.columns[3].order_field, 'category')
        self.assertEqual(smart_list.columns[3].order.column_id, 4)
Exemplo n.º 10
0
    def handle_export(self, request):
        try:
            export_backend = self.export_backends[int(
                request.GET[self.export_query_parameter_name])]
        except (IndexError, TypeError, ValueError):
            return redirect(request.path + self.get_url_with_query_params(
                {}, without=[self.export_query_parameter_name]))
        else:
            smart_list_settings = self.get_smart_list_settings()
            smart_list_instance = SmartList(
                self.get_queryset(),
                query_params=smart_list_settings['query_params'],
                list_display=smart_list_settings['list_display'],
                list_filter=smart_list_settings['list_filter'],
                list_search=smart_list_settings['list_search'],
                search_query_param=smart_list_settings['search_query_param'],
                ordering_query_param=smart_list_settings[
                    'ordering_query_param'],
                view=self,
            )

            value_rendering_context = make_context({},
                                                   request=request,
                                                   autoescape=False)

            def value_renderer(value):
                if isinstance(value, (Number, datetime.date)):
                    return value
                return render_value_in_context(value,
                                               context=value_rendering_context)

            response = HttpResponse(
                export_backend.get_content(smart_list_instance,
                                           value_renderer=value_renderer),
                content_type=export_backend.content_type,
            )
            response['Content-Disposition'] = 'attachment; filename={}'.format(
                export_backend.file_name)
            return response
Exemplo n.º 11
0
 def setUp(self):
     super(TestSmartListExportBackend, self).setUp()
     SampleModel.objects.create(title='First', category='blog_post')
     SampleModel.objects.create(title='Second', category='blog_post')
     self.smart_list = SmartList(SampleModel.objects.all(),
                                 list_display=('id', 'title', 'category'))
Exemplo n.º 12
0
    def test_columns(self):
        smart_list = SmartList(SampleModel.objects.all(),
                               list_display=('title', 'category'))

        self.assertEqual(len(smart_list.columns), 2)
Exemplo n.º 13
0
 def test_get_verbose_column_title_with_fallback(self):
     smart_list = SmartList(SampleModel.objects.all(),
                            **{'list_display': ('category', )})
     self.assertEqual('Category', smart_list.columns[0].get_title())
Exemplo n.º 14
0
 def test_get_column_from_method(self):
     smart_list = SmartList(SampleModel.objects.all(),
                            **{'list_display': ('some_display_method', )})
     self.assertEqual('Some Display Method',
                      smart_list.columns[0].get_title())