예제 #1
0
def report_generic(self, request, queryset):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s.pdf' % smart_str(queryset.model._meta.verbose_name.upper())

    html = html_report_generic(get_header(self, queryset), self.list_report, queryset)
    pdf = pisa.CreatePDF(html, response)

    return response
예제 #2
0
def report_generic(self, request, queryset):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s.pdf' % (
        smart_str(queryset.model._meta.verbose_name.upper()))

    local = settings.MEDIA_ROOT
    #campos = rtype.campos.replace('[', '').replace(']', '').replace('u\'', '').replace('\'', '').replace(',', '').split(' ')
    #list_report = []
    html = html_report_generic(get_header_detailed(self, queryset),
                               self.list_report, queryset)
    #html = html_report_generic(get_header_detailed(self, queryset), self.fieldsets_report, query)
    pdf = pisa.CreatePDF(html, response)
    return response
예제 #3
0
def report(request, report_id, template_name="report/report.html"):
    if request.user.is_staff:
        rtype = get_object_or_404(ReportType, id=report_id)
        if not request.user.is_superuser:
            if rtype.permissao.count() and not len([val for val in  rtype.permissao.all() if val in request.user.groups.all()]):
                raise Http404
        rtadmin = admin.site._registry[rtype.modelo.model_class()]

        campos_dinamicos = {}
        for filtro in rtadmin.list_filter:
            if type(filtro) == type(()):
                filtro = filtro[0]
            if "__" in filtro:
                filtro = filtro[:filtro.index("__")]
            field = get_field(rtype.modelo.model_class(), filtro)
            
            if type(field) == models.BooleanField:
                choices = (('1', _(u'Sim')), ('0', _(u'Não')), ('', _(u'Todos')))
                campos_dinamicos[filtro] = forms.ChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.RadioSelect())

            elif type(field) == models.CharField:
                if field.choices:
                    choices = field.choices
                    campos_dinamicos[filtro] = forms.MultipleChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.CheckboxSelectMultiple())
                else:
                    choices = set()
                    for obj in rtype.modelo.model_class().objects.all():
                        choices.add((get_value(obj, filtro), get_value(obj, filtro)))
                    choices = list(choices)
                    campos_dinamicos[filtro] = forms.MultipleChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.SelectMultiple())

            elif type(field) == models.DateField or type(field) == models.DateTimeField:
                choices = (('q', _(u'Qualquer data')), ('h', _(u'Hoje')), ('m', _(u'Este mês')), ('a', _(u'Este ano')))
                campos_dinamicos[filtro] = forms.ChoiceField(required=False, choices=choices, initial='q', label=_(field.verbose_name), widget=forms.RadioSelect())

            elif type(field) == models.ForeignKey or type(field) == models.OneToOneField:
                queryset = rtype.modelo.model_class()._meta.get_field(filtro).rel.to.objects.all()
                campos_dinamicos[filtro] = forms.ModelMultipleChoiceField(required=False, queryset=queryset, label=_(field.verbose_name), widget=forms.SelectMultiple())
            else:
                choices = set()
                for obj in rtype.modelo.model_class().objects.all():
                    choices.add((get_value(obj, filtro), get_value(obj, filtro)))
                choices = list(choices)
                campos_dinamicos[filtro] = forms.MultipleChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.SelectMultiple())

        FilterForm = type('', (forms.Form,), campos_dinamicos)

        if request.method == "POST":

            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s.pdf' % smart_str(rtype.titulo).replace(" ", "_")
            queryset = rtype.modelo.model_class().objects.all()

            for field_name in rtadmin.list_filter:
                field = get_field(rtype.modelo.model_class(), field_name)

                sql = {}
                if type(field) == models.DateField or type(field) == models.DateTimeField:
                    try:
                        value = request.POST[field_name]
                        if value == 'q': pass
                        elif value == 'h': sql["%s__day" % field_name] = datetime.now().day
                        elif value == 'm': sql["%s__month" % field_name] = datetime.now().month
                        elif value == 'a': sql["%s__year" % field_name] = datetime.now().year
                    except: pass
                elif type(field) == models.BooleanField:
                    try:
                        value = request.POST[field_name]
                        sql["%s" % field_name] = value
                    except: pass
                else:
                    try:
                        value = request.POST.getlist(field_name)
                        if len(value) == 0: continue
                        sql["%s__in" % field_name] = value
                    except: pass

                query = models.Q(**sql)
                queryset = queryset.filter(query)

            campos = rtype.campos.replace('[', '').replace(']', '').replace('u\'', '').replace('\'', '').replace(',', '').split(' ')
            list_report = []
            for c in campos:
               list_report.append(rtadmin.list_report[get_key(c)])
            try:
                model = str(queryset.model)
            except:
                model = str(queryset)
            if "PendenciaProcesso" in model:
                html = html_report_pendencias(smart_str(rtype.cabecalho), list_report, queryset)
            else:
                html = html_report_generic(smart_str(rtype.cabecalho), list_report, queryset)
            import logging

            class PisaNullHandler(logging.Handler):

                def emit(self, record):

                    pass
            log = logging.getLogger(__name__)
            log.addHandler(PisaNullHandler())
            pdf = pisa.CreatePDF(html, response)
            return response
        else:
            form = FilterForm()
            return render_to_response(template_name, {
                'form': form,
                'title': rtype.titulo,
                'rtype': rtype,
                'rtadmin' : rtadmin,
            }, context_instance=RequestContext(request))
    else:
        raise PermissionDenied
예제 #4
0
파일: views.py 프로젝트: adamrights/ors
def report(request, report_id, template_name="report/report.html"):
    if request.user.is_staff:
        rtype = get_object_or_404(ReportType, id=report_id)
        if not request.user.is_superuser:
            if rtype.permissao.count() and not len([val for val in  rtype.permissao.all() if val in request.user.groups.all()]):
                raise Http404
        rtadmin = admin.site._registry[rtype.modelo.model_class()]

        campos_dinamicos = {}
        for filtro in rtadmin.list_filter:

            field = get_field(rtype.modelo.model_class(), filtro)
            if type(field) == models.BooleanField:
                choices = (('1', _(u'Sim')), ('0', _(u'Não')), ('', _(u'Todos')))
                campos_dinamicos[filtro] = forms.ChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.RadioSelect())

            elif type(field) == models.CharField:
                if field.choices:
                    choices = field.choices
                    campos_dinamicos[filtro] = forms.MultipleChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.CheckboxSelectMultiple())
                else:
                    choices = set()
                    for obj in rtype.modelo.model_class().objects.all():
                        choices.add((get_value(obj, filtro), get_value(obj, filtro)))
                    choices = list(choices)
                    campos_dinamicos[filtro] = forms.MultipleChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.SelectMultiple())

            elif type(field) == models.DateField or type(field) == models.DateTimeField:
                choices = (('q', _(u'Qualquer data')), ('h', _(u'Hoje')), ('m', _(u'Este mês')), ('a', _(u'Este ano')))
                campos_dinamicos[filtro] = forms.ChoiceField(required=False, choices=choices, initial='q', label=_(field.verbose_name), widget=forms.RadioSelect())

            elif type(field) == models.ForeignKey or type(field) == models.OneToOneField:
                queryset = rtype.modelo.model_class()._meta.get_field(filtro).rel.to.objects.all()
                campos_dinamicos[filtro] = forms.ModelMultipleChoiceField(required=False, queryset=queryset, label=_(field.verbose_name), widget=forms.SelectMultiple())
            else:
                choices = set()
                for obj in rtype.modelo.model_class().objects.all():
                    choices.add((get_value(obj, filtro), get_value(obj, filtro)))
                choices = list(choices)
                campos_dinamicos[filtro] = forms.MultipleChoiceField(required=False, choices=choices, label=_(field.verbose_name), widget=forms.SelectMultiple())

        FilterForm = type('', (forms.Form,), campos_dinamicos)

        if request.method == "POST":

            response = HttpResponse(mimetype='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s.pdf' % smart_str(rtype.titulo).replace(" ", "_")
            queryset = rtype.modelo.model_class().objects.all()

            for field_name in rtadmin.list_filter:
                field = get_field(rtype.modelo.model_class(), field_name)

                sql = {}
                if type(field) == models.DateField or type(field) == models.DateTimeField:
                    try:
                        value = request.POST[field_name]
                        if value == 'q': pass
                        elif value == 'h': sql["%s__day" % field_name] = datetime.now().day
                        elif value == 'm': sql["%s__month" % field_name] = datetime.now().month
                        elif value == 'a': sql["%s__year" % field_name] = datetime.now().year
                    except: pass
                elif type(field) == models.BooleanField:
                    try:
                        value = request.POST[field_name]
                        sql["%s" % field_name] = value
                    except: pass
                else:
                    try:
                        value = request.POST.getlist(field_name)
                        if len(value) == 0: continue
                        sql["%s__in" % field_name] = value
                    except: pass

                query = models.Q(**sql)
                queryset = queryset.filter(query)

            campos = rtype.campos.replace('[', '').replace(']', '').replace('u\'', '').replace('\'', '').replace(',', '').split(' ')
            list_report = []
            for c in campos:
               list_report.append(rtadmin.list_report[get_key(c)])

            html = html_report_generic(smart_str(rtype.cabecalho), list_report, queryset)
            pdf = pisa.CreatePDF(html, response)
            return response
        else:
            form = FilterForm()
            return render_to_response(template_name, {
                'form': form,
                'title': rtype.titulo,
                'rtype': rtype,
                'rtadmin' : rtadmin,
            }, context_instance=RequestContext(request))
    else:
        raise PermissionDenied