Пример #1
0
    def test_result_list_html(self):
        """
        Regression test for #11791: Inclusion tag result_list generates a 
        table and this checks that the items are nested within the table
        element tags.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = MockRequest()
        m = ChildAdmin(Child, admin.site)
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                        m.list_filter, m.date_hierarchy, m.search_fields,
                        m.list_select_related, m.list_per_page,
                        m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template(
            '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
        )
        context = Context({'cl': cl})
        table_output = template.render(context)
        hidden_input_elem = '<input type="hidden" name="form-0-id" value="1" id="id_form-0-id" />'
        self.failIf(
            table_output.find(hidden_input_elem) == -1,
            'Failed to find expected hidden input element in: %s' %
            table_output)
        self.failIf(
            table_output.find('<td>%s</td>' % hidden_input_elem) == -1,
            'Hidden input element is not enclosed in <td> element.')

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                        m.list_filter, m.date_hierarchy, m.search_fields,
                        m.list_select_related, m.list_per_page,
                        m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template(
            '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
        )
        context = Context({'cl': cl})
        table_output = template.render(context)
        self.failIf(
            table_output.find(hidden_input_elem) == -1,
            'Failed to find expected hidden input element in: %s' %
            table_output)
        self.failIf(
            table_output.find('<td>%s</td>' % hidden_input_elem) == -1,
            'Hidden input element is not enclosed in <td> element.')
Пример #2
0
 def changelist_view(self, request, extra_context = None):
     if not self.has_change_permission(request, None):
         raise PermissionDenied
     
     if request.method == "GET":
         if "action" in request.GET:
             return grabar_ubicacion(request)
     opts = self.model._meta
     app_label = opts.app_label
     try:
         cl = ChangeList(request, self.model, self.list_display, self.list_display_links, self.list_filter,
             self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.change_list_template, self)
         cl.formset = None   
     except IncorrectLookupParameters:
         if ERROR_FLAG in request.GET.keys():
             return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
         return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
     lugar = place.objects.all()
     context = { 
         'title': 'Administracion de Ubicacion Tiendas',
         'is_popup': cl.is_popup,
         'cl': cl,
         'has_add_permission': self.has_add_permission(request),
         'root_path': self.admin_site.root_path,
         'app_label': app_label,
         'lugar':lugar,
     }
     context.update(extra_context or {})
     return render_to_response(self.change_list_template, context)
Пример #3
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name='parent')
     new_child = Child.objects.create(name='name', parent=new_parent)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, custom_site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(request, Child, list_display, list_display_links,
         m.list_filter, m.date_hierarchy, m.search_fields,
         m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m)
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">Parent object</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1,
         'Failed to find expected row element: %s' % table_output)
Пример #4
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name='parent')
     new_child = Child.objects.create(name='name', parent=new_parent)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(request, Child, list_display, list_display_links,
                     m.list_filter, m.date_hierarchy, m.search_fields,
                     m.list_select_related, m.list_per_page,
                     m.list_max_show_all, m.list_editable, m)
     cl.formset = None
     template = Template(
         '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
     )
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change',
                    args=(new_child.id, ))
     row_html = '<tbody><tr class="row1"><th><a href="%s">name</a></th><td class="nowrap">Parent object</td></tr></tbody>' % link
     self.assertFalse(
         table_output.find(row_html) == -1,
         'Failed to find expected row element: %s' % table_output)
Пример #5
0
 def test_result_list_set_empty_value_display_in_model_admin(self):
     """
     Test that empty value display can be set in ModelAdmin or individual fields.
     """
     new_child = Child.objects.create(name="name", parent=None)
     request = self.factory.get("/child/")
     m = EmptyValueChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(
         request,
         Child,
         list_display,
         list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_max_show_all,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-age_display">&dagger;</td><td class="field-age">-empty-</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output)
Пример #6
0
    def test_result_list_editable_html(self):
        """
        Regression tests for #11791: Inclusion tag result_list generates a
        table and this checks that the items are nested within the table
        element tags.
        Also a regression test for #13599, verifies that hidden fields
        when list_editable is enabled are rendered in a div outside the
        table.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = MockRequest()
        m = ChildAdmin(Child, admin.site)

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        # make sure that hidden fields are in the correct place
        hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></div>' % new_child.id
        self.assertFalse(table_output.find(hiddenfields_div) == -1,
            'Failed to find hidden fields in: %s' % table_output)
        # make sure that list editable fields are rendered in divs correctly
        editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />'
        self.assertFalse('<td>%s</td>' % editable_name_field == -1,
            'Failed to find "name" list_editable field in: %s' % table_output)
Пример #7
0
    def changelist_view(self, request, extra_context=None, **kwargs):
        """
        Sobrescreve o metodo changelist_view responsavel por exibir os dados do objeto,
        adicionando o total de IPs liberados e negados.
        Cria o arquivo texto usado pelos scripts de firewall e controle de banda.
        """

        from django.contrib.admin.views.main import ChangeList
        cl = ChangeList(request, self.model, list(self.list_display),
                        self.list_display_links, self.list_filter,
                        self.date_hierarchy, self.search_fields,
                        self.list_select_related,
                        self.list_per_page,
                        self.list_editable,
                        self)
        cl.formset = None

        if extra_context is None:
            extra_context = {}

        novo_arquivo_pontosrede = self._novo_arquivo_pontosrede()

        extra_context['cl'] = cl
        extra_context['total_liberados'] = novo_arquivo_pontosrede['total_liberados']
        extra_context['total_negados'] = novo_arquivo_pontosrede['total_negados']
        return super(PontoRedeAdmin, self).changelist_view(request, extra_context=extra_context)
Пример #8
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name="name", parent=None)
     request = self.factory.get("/child/")
     m = ChildAdmin(Child, custom_site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(
         request,
         Child,
         list_display,
         list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_max_show_all,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">-</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output)
Пример #9
0
 def test_result_list_set_empty_value_display_in_model_admin(self):
     """
     Test that empty value display can be set in ModelAdmin or individual fields.
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     m = EmptyValueChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(request, Child, list_display, list_display_links,
                     m.list_filter, m.date_hierarchy, m.search_fields,
                     m.list_select_related, m.list_per_page,
                     m.list_max_show_all, m.list_editable, m)
     cl.formset = None
     template = Template(
         '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
     )
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change',
                    args=(new_child.id, ))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-age_display">&amp;dagger;</td><td class="field-age">-empty-</td></tr></tbody>'
         % link)
     self.assertNotEqual(
         table_output.find(row_html), -1,
         'Failed to find expected row element: %s' % table_output)
Пример #10
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(request, Child, list_display, list_display_links,
                     m.list_filter, m.date_hierarchy, m.search_fields,
                     m.list_select_related, m.list_per_page,
                     m.list_max_show_all, m.list_editable, m)
     cl.formset = None
     template = Template(
         '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
     )
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change',
                    args=(new_child.id, ))
     row_html = '<tbody><tr class="row1"><th><a href="%s">name</a></th><td class="nowrap">(None)</td></tr></tbody>' % link
     self.assertFalse(
         table_output.find(row_html) == -1,
         'Failed to find expected row element: %s' % table_output)
Пример #11
0
    def test_result_list_editable_html(self):
        """
        Regression tests for #11791: Inclusion tag result_list generates a
        table and this checks that the items are nested within the table
        element tags.
        Also a regression test for #13599, verifies that hidden fields
        when list_editable is enabled are rendered in a div outside the
        table.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, admin.site)

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, m.list_display, m.list_display_links,
                m.list_filter, m.date_hierarchy, m.search_fields,
                m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        # make sure that hidden fields are in the correct place
        hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></div>' % new_child.id
        self.assertFalse(table_output.find(hiddenfields_div) == -1,
            'Failed to find hidden fields in: %s' % table_output)
        # make sure that list editable fields are rendered in divs correctly
        editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />'
        self.assertFalse('<td>%s</td>' % editable_name_field == -1,
            'Failed to find "name" list_editable field in: %s' % table_output)
Пример #12
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name="parent")
     new_child = Child.objects.create(name="name", parent=new_parent)
     request = self.factory.get("/child/")
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(
         request,
         Child,
         list_display,
         list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_max_show_all,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     row_html = (
         '<tbody><tr class="row1"><th><a href="%d/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>'
         % new_child.id
     )
     self.assertFalse(table_output.find(row_html) == -1, "Failed to find expected row element: %s" % table_output)
Пример #13
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name="name", parent=None)
     request = MockRequest()
     m = ChildAdmin(Child, admin.site)
     cl = ChangeList(
         request,
         Child,
         m.list_display,
         m.list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td class="nowrap">(None)</td></tr></tbody>'
     self.assertFalse(table_output.find(row_html) == -1, "Failed to find expected row element: %s" % table_output)
Пример #14
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name="parent")
     new_child = Child.objects.create(name="name", parent=new_parent)
     request = MockRequest()
     m = ChildAdmin(Child, admin.site)
     cl = ChangeList(
         request,
         Child,
         m.list_display,
         m.list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>'
     self.assertFalse(table_output.find(row_html) == -1, "Failed to find expected row element: %s" % table_output)
Пример #15
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name='parent')
     new_child = Child.objects.create(name='name', parent=new_parent)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, custom_site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template(
         '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
     )
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change',
                    args=(new_child.id, ))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">Parent object</td></tr></tbody>' %
         link)
     self.assertNotEqual(
         table_output.find(row_html), -1,
         'Failed to find expected row element: %s' % table_output)
Пример #16
0
    def test_result_list_with_allow_tags(self):
        """
        Test for deprecation of allow_tags attribute
        """
        new_parent = Parent.objects.create(name='parent')
        for i in range(2):
            Child.objects.create(name='name %s' % i, parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, custom_site)

        def custom_method(self, obj=None):
            return 'Unsafe html <br />'
        custom_method.allow_tags = True

        # Add custom method with allow_tags attribute
        m.custom_method = custom_method
        m.list_display = ['id', 'name', 'parent', 'custom_method']

        cl = ChangeList(request, Child, *get_changelist_args(m))
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        custom_field_html = '<td class="field-custom_method">Unsafe html <br /></td>'
        self.assertInHTML(custom_field_html, table_output)
Пример #17
0
 def test_result_list_set_empty_value_display_on_admin_site(self):
     """
     Test that empty value display can be set on AdminSite
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     # Set a new empty display value on AdminSite.
     admin.site.empty_value_display = '???'
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(request, Child, list_display, list_display_links,
         m.list_filter, m.date_hierarchy, m.search_fields,
         m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m)
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">???</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1,
         'Failed to find expected row element: %s' % table_output)
Пример #18
0
def export(request, admin_site, model_name, app_label, format='csv'):
    if not request.user.is_staff:
        return HttpResponseForbidden()

    if not format in ALLOWED_EXPORT_TYPES:
        raise Http404('%s is not a supported format.' % format)

    model = get_model(app_label, model_name)
    model_admin = None

    for entry in admin_site._registry:
        if entry._meta.object_name == model._meta.object_name:
            model_admin = admin_site._registry[entry]

    if model_admin == None:
        raise Http404('ModelAdmin for model %s.%s not found' % (app_label, model_name))

    cl = ChangeList(request, model, list(model_admin.list_display), model_admin.list_display_links,
                    model_admin.list_filter, model_admin.date_hierarchy, model_admin.search_fields,
                    model_admin.list_select_related, model_admin.list_per_page, model_admin.list_editable,
                    model_admin)
    cl.formset = None

    c = RequestContext(request)
    if 'template' in ALLOWED_EXPORT_TYPES[format]:
        rows = []
        headers = []

        for field in model._meta.fields:
            headers.append(field.name)

        rows.append(headers)

        for record in cl.query_set:
            column = []

            for field in headers:
                val = getattr(record, field)

                if callable(val):
                    val = val()

                val = smart_str(val)
                column.append(val)

            rows.append(column)

        t = loader.get_template(ALLOWED_EXPORT_TYPES[format]['template'])
        c['rows'] = rows
        responseContents = t.render(c)
    elif 'serializer' in ALLOWED_EXPORT_TYPES[format]:
        responseContents = serialize(ALLOWED_EXPORT_TYPES[format]['serializer'], cl.query_set.all())
    else:
        raise Http404('Export type for %s must have value for template or serializer' % format)

    response = HttpResponse(responseContents, mimetype=ALLOWED_EXPORT_TYPES[format]['mimetype'])
    response['Content-Disposition'] = 'attachment; filename=%s' % (ALLOWED_EXPORT_TYPES[format]['filename'] % slugify(model_name))

    return response
Пример #19
0
 def changelist_view(self, request, extra_context = None):
     compras = ""
     ciudad = ""
     
     lista = []
     lista_usd = []
     lista_ciudad = []
     tipo_cambio = 0
     cambio = 0
     if not self.has_change_permission(request, None):
         raise PermissionDenied
     opts = self.model._meta
     app_label = opts.app_label
     
     compras = Compra.objects.all().order_by("-fecha_pedido").filter(abono = False).filter(status = "A")
     ciudad = Ciudad.objects.all().distinct()
     
     for i in ciudad:
         city_str = str(i.nombre)
         total = 0
         total_usd = 0
         for j in compras:
             lugar_str = str(j.direccion_entrega.ciudad)
             if lugar_str == city_str:
                 total += j.total
                 tipo_cambio = float(get_tipo_cambio())
                 total_usd = round(total/tipo_cambio, 2)
             else:
                 pass
         lista.append(total)
         lista_usd.append(total_usd)
         lista_ciudad.append(i.nombre)
         
     try:
         cl = ChangeList(request, self.model, self.list_display, self.list_display_links, self.list_filter,
             self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.change_list_template, self)
         cl.formset = None   
     except IncorrectLookupParameters:
         if ERROR_FLAG in request.GET.keys():
             return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
         return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
     
     context = { 
         'title': 'Administracion de Totales por Tienda',
         'is_popup': cl.is_popup,
         'cl': cl,
         'has_add_permission': self.has_add_permission(request),
         'root_path': self.admin_site.root_path,
         'app_label': app_label,
         'compra':compras,
         'total':lista,
         'city':lista_ciudad,
         'cambio':lista_usd,
         
     }
     context.update(extra_context or {})
     return render_to_response(self.change_list_template, context)
Пример #20
0
    def test_result_list_editable_html(self):
        """
        Regression tests for #11791: Inclusion tag result_list generates a
        table and this checks that the items are nested within the table
        element tags.
        Also a regression test for #13599, verifies that hidden fields
        when list_editable is enabled are rendered in a div outside the
        table.
        """
        new_parent = Parent.objects.create(name="parent")
        new_child = Child.objects.create(name="name", parent=new_parent)
        request = self.factory.get("/child/")
        m = ChildAdmin(Child, custom_site)

        # Test with list_editable fields
        m.list_display = ["id", "name", "parent"]
        m.list_display_links = ["id"]
        m.list_editable = ["name"]
        cl = ChangeList(
            request,
            Child,
            m.list_display,
            m.list_display_links,
            m.list_filter,
            m.date_hierarchy,
            m.search_fields,
            m.list_select_related,
            m.list_per_page,
            m.list_max_show_all,
            m.list_editable,
            m,
        )
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
        context = Context({"cl": cl})
        table_output = template.render(context)
        # make sure that hidden fields are in the correct place
        hiddenfields_div = (
            '<div class="hiddenfields">'
            '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" />'
            "</div>"
        ) % new_child.id
        self.assertInHTML(hiddenfields_div, table_output, msg_prefix="Failed to find hidden fields")

        # make sure that list editable fields are rendered in divs correctly
        editable_name_field = (
            '<input name="form-0-name" value="name" class="vTextField" '
            'maxlength="30" type="text" id="id_form-0-name" />'
        )
        self.assertInHTML(
            '<td class="field-name">%s</td>' % editable_name_field,
            table_output,
            msg_prefix='Failed to find "name" list_editable field',
        )
Пример #21
0
def obtener_listado_admin(
  self,
  model,
  my_admin=CustomModelAdmin,
  queryset=None):
  
  #custom_site.register(model,model)

  my_admin = my_admin(model,custom_site)
  if queryset != None:
    nuevo_queryset = queryset
    my_admin.set_queryset(nuevo_queryset)
    
  list_display = ['action_checkbox'] + list(my_admin.list_display)
  
  my_admin.show_admin_actions = True
  my_admin.actions = my_admin.get_actions(self)
  action_form = my_admin.action_form(self.POST)
  action_form.fields['action'].choices = my_admin.get_action_choices(self)

  ChangeList = my_admin.get_changelist(self)

  listado = ChangeList(
    self,
    model,
    list_display,
    my_admin.get_list_display_links(self,my_admin.list_display),
    my_admin.list_filter,
    my_admin.date_hierarchy,
    my_admin.search_fields,
    my_admin.list_select_related,
    my_admin.list_per_page,
    my_admin.list_max_show_all,
    my_admin.list_editable,
    my_admin)
  
  selected = self.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

  if selected:
    response = my_admin.response_action(self,queryset=listado.get_queryset(self))
    if type(response) is HttpResponse:
      return response
  
  #if not selected and self.POST:
  #  messages.error(self, 'No selecciono ningun elemento. No se afecto ningún elemento')

  listado.formset = None

  parametros = {
    'cl'                        : listado,
    'action_form'               : action_form,
    'actions_selection_counter' : my_admin.actions_selection_counter
  }

  return parametros
Пример #22
0
    def test_result_list_html(self):
        """
        Regression test for #11791: Inclusion tag result_list generates a 
        table and this checks that the items are nested within the table
        element tags.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = MockRequest()
        m = ChildAdmin(Child, admin.site)
        cl = ChangeList(request, Child, m.list_display, m.list_display_links, 
                m.list_filter, m.date_hierarchy, m.search_fields, 
                m.list_select_related, m.list_per_page, m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        hidden_input_elem = '<input type="hidden" name="form-0-id" value="1" id="id_form-0-id" />' 
        self.failIf(table_output.find(hidden_input_elem) == -1,
            'Failed to find expected hidden input element in: %s' % table_output)
        self.failIf(table_output.find('<td>%s</td>' % hidden_input_elem) == -1,
            'Hidden input element is not enclosed in <td> element.')

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, m.list_display, m.list_display_links, 
                m.list_filter, m.date_hierarchy, m.search_fields, 
                m.list_select_related, m.list_per_page, m.list_editable, m)
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        self.failIf(table_output.find(hidden_input_elem) == -1,
            'Failed to find expected hidden input element in: %s' % table_output)
        self.failIf(table_output.find('<td>%s</td>' % hidden_input_elem) == -1,
            'Hidden input element is not enclosed in <td> element.')
Пример #23
0
 def test_render_tag(self):
     request = RequestFactory().get('/')
     t = Template('{% load position_tags %}{% position_result_list cl %}')
     change_list = ChangeList(
         request=request, model=DummyModel, list_display=['name'],
         list_display_links=None, list_filter=None, date_hierarchy=None,
         search_fields=None, list_select_related=None, list_per_page=100,
         list_max_show_all=10, list_editable=None,
         model_admin=GenericPositionsAdmin(DummyModel, AdminSite()))
     change_list.formset = None
     c = Context({'cl': change_list})
     self.assertIn('name="position-{0}"'.format(self.first_model.id),
                   t.render(c))
Пример #24
0
def obtener_listado(
  self,
  model,
  list_display=[],
  list_display_links=None,
  list_filter=[],
  date_hierarchy=None,
  search_fields=[],
  list_per_page=500,
  list_max_show_all=5000,
  queryset=None):
  
  my_admin = CustomModelAdmin
  my_admin                     = my_admin(model,AdminSite())
  my_admin.list_display        = list_display
  my_admin.list_display_links  = list_display_links
  my_admin.list_filter         = list_filter
  my_admin.date_hierarchy      = date_hierarchy
  my_admin.search_fields       = search_fields
  my_admin.list_select_related = ''
  my_admin.list_per_page       = list_per_page
  my_admin.list_max_show_all   = list_max_show_all
  my_admin.list_editable       = []
  my_admin.actions             = []
  my_admin.action_form         = helpers.ActionForm

  if queryset != None:
    nuevo_queryset = queryset
    my_admin.set_queryset(nuevo_queryset)

  ChangeList = my_admin.get_changelist(self)

  listado = ChangeList(
    self,
    model,
    my_admin.list_display,
    my_admin.list_display_links,
    my_admin.list_filter,
    my_admin.date_hierarchy,
    my_admin.search_fields,
    my_admin.list_select_related,
    my_admin.list_per_page,
    my_admin.list_max_show_all,
    my_admin.list_editable,
    my_admin)

  listado.formset = None

  return listado
Пример #25
0
    def day_view(self, request, extra_context=None):
        from django.contrib.admin.views.main import ChangeList, ERROR_FLAG
        opts = self.model._meta
        app_label = opts.app_label
        reduced_view = request.GET.pop('reduced_view', False)

        try:
            cl = ChangeList(request, self.model, self.list_display, self.list_display_links, self.list_filter,
                self.date_hierarchy, self.search_fields, self.list_select_related, self.list_per_page, self.list_editable, self)
        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given and
            # the 'invalid=1' parameter was already in the query string, something
            # is screwed up with the database, so display an error page.
            if ERROR_FLAG in request.GET.keys():
                return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        cl.formset = None
        day = int(request.GET.get('broadcast_date__day'))
        month = int(request.GET.get('broadcast_date__month'))
        year = int(request.GET.get('broadcast_date__year'))
        day = datetime.datetime(year, month, day)
        context = {
            'title': cl.title,
            'is_popup': cl.is_popup,
            'cl': cl,
            'has_add_permission': self.has_add_permission(request),
            'root_path': self.admin_site.root_path,
            'app_label': app_label,
            'actual_date': '%s de %s de %s' % (day.day, smart_str(MONTHS[day.month]), day.year),
            'days': [{'name': WEEKDAYS[day.weekday()],
                      'index': day.weekday(),
                      'date': day.date(),
                     }],
            'hours': self.get_hours(WEEK_HOURS_DELTA),
            'hoursdelta': WEEK_HOURS_DELTA.seconds,
            'reduced_view': reduced_view,
            'base_date': day,
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(request, current_app=self.admin_site.name)
        return render_to_response(self.day_view_template,
                                  context, context_instance=context_instance)
Пример #26
0
 def test_result_list_set_empty_value_display_in_model_admin(self):
     """
     Empty value display can be set in ModelAdmin or individual fields.
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     m = EmptyValueChildAdmin(Child, admin.site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-age_display">&amp;dagger;</td><td class="field-age">-empty-</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
Пример #27
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = MockRequest()
     m = ChildAdmin(Child, admin.site)
     cl = ChangeList(request, Child, m.list_display, m.list_display_links,
             m.list_filter, m.date_hierarchy, m.search_fields,
             m.list_select_related, m.list_per_page, m.list_editable, m)
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     row_html = '<tbody><tr class="row1"><td><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td>(None)</td></tr></tbody>'
     self.assertFalse(table_output.find(row_html) == -1,
         'Failed to find expected row element: %s' % table_output)
Пример #28
0
    def test_result_list_editable_html(self):
        """
        Regression tests for #11791: Inclusion tag result_list generates a
        table and this checks that the items are nested within the table
        element tags.
        Also a regression test for #13599, verifies that hidden fields
        when list_editable is enabled are rendered in a div outside the
        table.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, custom_site)

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, *get_changelist_args(m))
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template(
            '{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}'
        )
        context = Context({'cl': cl})
        table_output = template.render(context)
        # make sure that hidden fields are in the correct place
        hiddenfields_div = (
            '<div class="hiddenfields">'
            '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" />'
            '</div>') % new_child.id
        self.assertInHTML(hiddenfields_div,
                          table_output,
                          msg_prefix='Failed to find hidden fields')

        # make sure that list editable fields are rendered in divs correctly
        editable_name_field = (
            '<input name="form-0-name" value="name" class="vTextField" '
            'maxlength="30" type="text" id="id_form-0-name" />')
        self.assertInHTML(
            '<td class="field-name">%s</td>' % editable_name_field,
            table_output,
            msg_prefix='Failed to find "name" list_editable field',
        )
Пример #29
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, custom_site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">-</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
Пример #30
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name='parent')
     new_child = Child.objects.create(name='name', parent=new_parent)
     request = MockRequest()
     m = ChildAdmin(Child, admin.site)
     cl = ChangeList(request, Child, m.list_display, m.list_display_links,
             m.list_filter, m.date_hierarchy, m.search_fields,
             m.list_select_related, m.list_per_page, m.list_editable, m)
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     row_html = '<tbody><tr class="row1"><td><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td>Parent object</td></tr></tbody>'
     self.assertFalse(table_output.find(row_html) == -1,
         'Failed to find expected row element: %s' % table_output)
Пример #31
0
    def test_result_list_editable_html(self):
        """
        Regression tests for #11791: Inclusion tag result_list generates a
        table and this checks that the items are nested within the table
        element tags.
        Also a regression test for #13599, verifies that hidden fields
        when list_editable is enabled are rendered in a div outside the
        table.
        """
        new_parent = Parent.objects.create(name='parent')
        new_child = Child.objects.create(name='name', parent=new_parent)
        request = self.factory.get('/child/')
        m = ChildAdmin(Child, custom_site)

        # Test with list_editable fields
        m.list_display = ['id', 'name', 'parent']
        m.list_display_links = ['id']
        m.list_editable = ['name']
        cl = ChangeList(request, Child, *get_changelist_args(m))
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
        context = Context({'cl': cl})
        table_output = template.render(context)
        # make sure that hidden fields are in the correct place
        hiddenfields_div = (
            '<div class="hiddenfields">'
            '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" />'
            '</div>'
        ) % new_child.id
        self.assertInHTML(hiddenfields_div, table_output, msg_prefix='Failed to find hidden fields')

        # make sure that list editable fields are rendered in divs correctly
        editable_name_field = (
            '<input name="form-0-name" value="name" class="vTextField" '
            'maxlength="30" type="text" id="id_form-0-name" />'
        )
        self.assertInHTML(
            '<td class="field-name">%s</td>' % editable_name_field,
            table_output,
            msg_prefix='Failed to find "name" list_editable field',
        )
Пример #32
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name="parent")
     new_child = Child.objects.create(name="name", parent=new_parent)
     request = self.factory.get("/child/")
     m = ChildAdmin(Child, custom_site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">Parent object</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output)
Пример #33
0
 def test_result_list_set_empty_value_display_on_admin_site(self):
     """
     Test that empty value display can be set on AdminSite
     """
     new_child = Child.objects.create(name="name", parent=None)
     request = self.factory.get("/child/")
     # Set a new empty display value on AdminSite.
     admin.site.empty_value_display = "???"
     m = ChildAdmin(Child, admin.site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     link = reverse("admin:admin_changelist_child_change", args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">???</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output)
Пример #34
0
 def test_render_tag(self):
     request = RequestFactory().get('/')
     t = Template('{% load position_tags %}{% position_result_list cl %}')
     change_list = ChangeList(request=request,
                              model=DummyModel,
                              list_display=['name'],
                              list_display_links=None,
                              list_filter=None,
                              date_hierarchy=None,
                              search_fields=None,
                              list_select_related=None,
                              list_per_page=100,
                              list_max_show_all=10,
                              list_editable=None,
                              model_admin=GenericPositionsAdmin(
                                  DummyModel, AdminSite()))
     change_list.formset = None
     c = Context({'cl': change_list})
     self.assertIn('name="position-{0}"'.format(self.first_model.id),
                   t.render(c))
Пример #35
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, custom_site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">-</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1,
         'Failed to find expected row element: %s' % table_output)
Пример #36
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(request, Child, list_display, list_display_links,
             m.list_filter, m.date_hierarchy, m.search_fields,
             m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m)
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     row_html = '<tbody><tr class="row1"><th><a href="%d/">name</a></th><td class="nowrap">(None)</td></tr></tbody>' % new_child.id
     self.assertFalse(table_output.find(row_html) == -1,
         'Failed to find expected row element: %s' % table_output)
Пример #37
0
 def test_result_list_set_empty_value_display_on_admin_site(self):
     """
     Test that empty value display can be set on AdminSite
     """
     new_child = Child.objects.create(name='name', parent=None)
     request = self.factory.get('/child/')
     # Set a new empty display value on AdminSite.
     admin.site.empty_value_display = '???'
     m = ChildAdmin(Child, admin.site)
     cl = ChangeList(request, Child, *get_changelist_args(m))
     cl.formset = None
     template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
     context = Context({'cl': cl})
     table_output = template.render(context)
     link = reverse('admin:admin_changelist_child_change', args=(new_child.id,))
     row_html = (
         '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
         '<td class="field-parent nowrap">???</td></tr></tbody>' % link
     )
     self.assertNotEqual(table_output.find(row_html), -1,
         'Failed to find expected row element: %s' % table_output)
Пример #38
0
    def test_result_list_with_allow_tags(self):
        """
        Test for deprecation of allow_tags attribute
        """
        new_parent = Parent.objects.create(name="parent")
        for i in range(2):
            Child.objects.create(name="name %s" % i, parent=new_parent)
        request = self.factory.get("/child/")
        m = ChildAdmin(Child, custom_site)

        def custom_method(self, obj=None):
            return "Unsafe html <br />"

        custom_method.allow_tags = True

        # Add custom method with allow_tags attribute
        m.custom_method = custom_method
        m.list_display = ["id", "name", "parent", "custom_method"]

        cl = ChangeList(
            request,
            Child,
            m.list_display,
            m.list_display_links,
            m.list_filter,
            m.date_hierarchy,
            m.search_fields,
            m.list_select_related,
            m.list_per_page,
            m.list_max_show_all,
            m.list_editable,
            m,
        )
        FormSet = m.get_changelist_formset(request)
        cl.formset = FormSet(queryset=cl.result_list)
        template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
        context = Context({"cl": cl})
        table_output = template.render(context)
        custom_field_html = '<td class="field-custom_method">Unsafe html <br /></td>'
        self.assertInHTML(custom_field_html, table_output)
Пример #39
0
    def changelist_view(self, request, extra_context=None):
        from django.contrib.admin.views.main import ChangeList, ERROR_FLAG
        try:
            cl = ChangeList(request, self.model, self.list_display,
                            self.list_display_links, self.list_filter,
                            self.date_hierarchy, self.search_fields,
                            self.list_select_related, self.list_per_page,
                            self.list_editable, self)
            cl.formset = None
        except IncorrectLookupParameters:
            if ERROR_FLAG in request.GET.keys():
                return render_to_response(
                    'admin/invalid_setup.html',
                    {'title': ugettext('Database error')})
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        class_name = getattr(request, 'CLASS_NAME', None)
        cl.has_filters = True
        class_names = [{
            'name': ugettext('All'),
            'url': cl.get_query_string(remove='class_name')
        }]
        for i in BaseContent.objects.order_by('class_name').values(
                'class_name').distinct():
            class_names.append({
                'name':
                i['class_name'],
                'url':
                cl.get_query_string(new_params={'class_name': i['class_name']})
            })
        if class_name:
            cl.params.update({'class_name': class_name})

        context = {
            'cl': cl,
            'class_names': class_names,
        }
        context.update(extra_context or {})
        return super(PhotoAdmin, self).changelist_view(request, context)
Пример #40
0
    def changelist_view(self, request, extra_context=None):
        from django.contrib.admin.views.main import ChangeList, ERROR_FLAG

        try:
            cl = ChangeList(
                request,
                self.model,
                self.list_display,
                self.list_display_links,
                self.list_filter,
                self.date_hierarchy,
                self.search_fields,
                self.list_select_related,
                self.list_per_page,
                self.list_editable,
                self,
            )
            cl.formset = None
        except IncorrectLookupParameters:
            if ERROR_FLAG in request.GET.keys():
                return render_to_response("admin/invalid_setup.html", {"title": ugettext("Database error")})
            return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1")

        class_name = getattr(request, "CLASS_NAME", None)
        cl.has_filters = True
        class_names = [{"name": ugettext("All"), "url": cl.get_query_string(remove="class_name")}]
        for i in BaseContent.objects.order_by("class_name").values("class_name").distinct():
            class_names.append(
                {"name": i["class_name"], "url": cl.get_query_string(new_params={"class_name": i["class_name"]})}
            )
        if class_name:
            cl.params.update({"class_name": class_name})

        context = {"cl": cl, "class_names": class_names}
        context.update(extra_context or {})
        return super(PhotoAdmin, self).changelist_view(request, context)
Пример #41
0
 def context(self, extra_context = None):
     """
     Generate the context needed by django_relatedcontent/select_change_list.html
     to render a modified change_list template similar to the django.contrib.admin.
     """
     from django.contrib.admin.views.main import ChangeList, ERROR_FLAG
     import django.http as http
     import copy
     
     additional_params = self.parse_query_params()
     current_related_objects = self.get_related_objects()
     
     opts = self.selectable_model._meta
     app_label = opts.app_label
     
     try:
         list_display = copy.deepcopy(self.admin.list_display)
         for field_name in settings.VOID_ADMIN_FIELD_NAMES:
             list_display.remove(field_name)
             
         cl = ChangeList(self.request, 
                         self.admin.model, 
                         list_display, 
                         self.admin.list_display_links, 
                         self.admin.list_filter,
                         self.admin.date_hierarchy,
                         self.admin.search_fields,
                         self.admin.list_select_related,
                         self.admin.list_per_page,
                         self.admin.list_editable,
                         self.admin)
         cl.formset = None
         cl.related_objects = current_related_objects
         cl.title = "Select %s to add" % (opts.verbose_name)
     except Exception, e:
         raise Exception(e)
Пример #42
0
    def change_view(self, request, object_id, extra_context=None):
        content_obj = self.model.objects.get(id=object_id)
        objects = content_obj.model_class().objects.all()
        cl = objects
        list_display = ('__str__',)
        list_display = [x.name for x in content_obj.model_class()._meta.fields]
        list_display_links = ()
        list_filter = ()
        list_select_related = False
        list_per_page = 40
        list_editable = ()
        search_fields = ()
        date_hierarchy = None
        save_as = False
        save_on_top = False
        ordering = None
        inlines = [] 
        
        # create model admin for such class
        current_model_admin = admin.ModelAdmin(content_obj.model_class(), AdminSite())
        
        # create Change list object.
        cl = ChangeList(request, content_obj.model_class(), list_display, list_display_links, list_filter,
                date_hierarchy, search_fields, list_select_related, list_per_page, list_editable, current_model_admin)
        
        cl.formset = None
        
        # what information about object to show in the admin panel 
        # all of them are attributes of model instance
        model_attrs = ["object_name", "db_table", "verbose_name", "proxy", "app_label",
                        "module_name"]

        model_info = []
        
        for attr in model_attrs:
            model_info.append({"name": attr, "value": cl.model._meta.__getattribute__(attr)})
        
        # what information about fields to show in the admin
        model_fields = {}
        model_fields["header"] = ["name", "internal_type", "max_length", "verbose_name",  
                                "unique", "rel", "null", "primary_key", "blank", "column", 
                                "db_column", "db_type", "db_index"]

        model_fields["fields"] = []
        for field in cl.model._meta.fields:
            field_list = []
            for attr in model_fields["header"]:
                # internal type is callable attribute
                if attr == "internal_type":
                    field_list.append(field.get_internal_type())
                    continue
                if attr == "db_type":
                    field_list.append(field.db_type())
                    continue
                attrib = field.__getattribute__(attr)
                if attr == "rel" and attrib:
                    field_list.append(attrib.to)
                    continue
                field_list.append(attrib)
                
            model_fields["fields"].append(field_list)

        return super(ContentTypeProxyAdmin, self).change_view(request, object_id, extra_context={"cl": cl,
                                                                                                 "model_info": model_info,
                                                                                                 "model_fields": model_fields})
Пример #43
0
    def day_view(self, request, extra_context=None):
        from django.contrib.admin.views.main import ChangeList, ERROR_FLAG
        opts = self.model._meta
        app_label = opts.app_label
        reduced_view = request.GET.pop('reduced_view', False)

        try:
            cl = ChangeList(request, self.model, self.list_display,
                            self.list_display_links, self.list_filter,
                            self.date_hierarchy, self.search_fields,
                            self.list_select_related, self.list_per_page,
                            self.list_editable, self)
        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given and
            # the 'invalid=1' parameter was already in the query string, something
            # is screwed up with the database, so display an error page.
            if ERROR_FLAG in request.GET.keys():
                return render_to_response('admin/invalid_setup.html',
                                          {'title': _('Database error')})
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        cl.formset = None
        day = int(request.GET.get('broadcast_date__day'))
        month = int(request.GET.get('broadcast_date__month'))
        year = int(request.GET.get('broadcast_date__year'))
        day = datetime.datetime(year, month, day)
        context = {
            'title':
            cl.title,
            'is_popup':
            cl.is_popup,
            'cl':
            cl,
            'has_add_permission':
            self.has_add_permission(request),
            'root_path':
            self.admin_site.root_path,
            'app_label':
            app_label,
            'actual_date':
            '%s de %s de %s' %
            (day.day, smart_str(MONTHS[day.month]), day.year),
            'days': [{
                'name': WEEKDAYS[day.weekday()],
                'index': day.weekday(),
                'date': day.date(),
            }],
            'hours':
            self.get_hours(WEEK_HOURS_DELTA),
            'hoursdelta':
            WEEK_HOURS_DELTA.seconds,
            'reduced_view':
            reduced_view,
            'base_date':
            day,
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(self.day_view_template,
                                  context,
                                  context_instance=context_instance)