generate a pdf only with arguments passed by a Django form

Asked

Viewed 355 times

1

Hello, I’m having a problem generating a pdf, I need to create filters for a more detailed report, my code consists of a simple view of Template where I set up the form with the "GET" method, and a function where my pdf is generated. the problem is that the filters I select in Templateview do not pass to the pdf function. any hints? I thank you already.

view of the creation of the form

class SolicitacaoReport(PermissionRequiredMixin, TemplateView):
    permission_required = 'administrativo_permissao'
    raise_exception = True
    template_name='administrativo/home.html'

    def get_context_data(self, **kwargs):
        context = super(SolicitacaoReport, self).get_context_data(**kwargs)
        context['usuarios'] = User.objects.select_related().order_by('username')
        context['departamentos'] = Departamento.objects.select_related().order_by('nome_departamento')
        return context

pdf creation view

def solicitacao_report(request):
    resp = HttpResponse(content_type='application/pdf')

    if request.method == 'GET':
        user = request.GET.get('usuario')
        data_emissao = request.GET.get('departamento_relacionamento')


    solicitacoes = Solicitacao.objects.order_by('user', 'data_emissao', 'departamento_relacionamento')
    report = SolicitacaoListReport(queryset=solicitacoes)
    report.generate_by(PDFGenerator, filename=resp)

    return resp

html form.

<form method="GET" novalidate>
    {% csrf_token %}
        <div class="row mx-auto">
            <div>
                <div class="form-group">
                    <p>Usuário</p>
                    <select class="form-control" id="usuarios" name='usuario'>
                        <option>--------</option>
                        {% for usuario in usuarios %}
                         <option>{{usuario.name}}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-group">
                    <p>Numero Requisição</p>
                    <input type="email" class="form-control" id="requisicao" placeholder="N°" name='requisicaoForm'>
                </div>
            </div>
            <div>
                <div class="form-group">
                    <p>Data De</p>
                    <input id="dateDe" placeholder="00/00/0000" name='dataDe' />    
                </div>
                <div class="form-group">
                    <p>Departamento</p>
                    <select class="form-control" id="usuarios" name='departamentoForm'>
                        <option>--------</option>
                        {% for departamento in departamentos %}
                        <option>{{departamento.nome_departamento}}</option>
                        {% endfor %}
                    </select>   
                </div>
            </div>
            <div>
                <div class="form-group">
                    <p>Ate</p>
                    <input id="dateATE" placeholder="00/00/0000" name='dataAte' />  
                </div>
            </div>                  
        </div>
    <dir>
        <a class="btn btn-warning" type="submit" href="{% url 'teste' %}">Imprimir</a>
    </dir>
</form>

I’m new in web so I’m stuck in this for a long time already, I thank you help

I’m using the marine Geraldo Reports updated by Thiago Pena to run in python 3

EDIT

I am already able to take the information and use it in the function the problem that even receiving the GET values the filter still doesn’t work.

View’s

class SolicitacaoReport(PermissionRequiredMixin, TemplateView):
permission_required = 'administrativo_permissao'
raise_exception = True
template_name='administrativo/home.html'

def get(self, request, *args, **kwargs):
    context = self.get_context_data(**kwargs)
    context['usuarios'] = User.objects.select_related().order_by('username')
    context['departamentos'] = Departamento.objects.select_related().order_by('nome_departamento')
    return self.render_to_response(context)

function that receives the data and generates the pdf

def solicitacao_report(request):
resp = HttpResponse(content_type='application/pdf')

if request.method == 'GET':
    user = request.GET.get("usuario")
    data_emissao = request.GET.get("departamento_relacionamento")


solicitacoes = Solicitacao.objects.order_by('user', 'data_emissao', 'departamento_relacionamento')

if user:
    solicitacoes.filter(user=user)

report = SolicitacaoListReport(queryset=solicitacoes)
report.generate_by(PDFGenerator, filename=resp)

return resp

in html I made a change by switching a href to an input with type Submit and passed the url to the form action.

the address url looks like this when I select an option in the filter and give the Submit

http://127.0.0.1:8000/request/administrative/system/summary/filters/pdf? csrfmiddlewaretoken=7Pcb4f20M5maPHYmED3tTSXmVDY2m62iR6MfXYJzZn3syONTASVVZ0cQ6D0NRYdS&usuario=1&requisicaoForm=&dataDe=&departamentoForm=--------&dataAte=

as you can see in the url it brings the id of my user the problem that even taking the information with GET I can’t use them to make the filter

  • 1

    I’m finding your question a little obscure. What’s your problem? What’s going wrong? What do you want? In summary it would be: Get data from a form and treat them? In case assemble a pdf with this data, it is this?

  • That’s right, sorry I wanted to give a more detailed explanation and I ended up doing the opposite.

  • Okay, see if you can get my answer

1 answer

1


You would have much more flexibility if you used the Forms of the own Django, ai Voce could continue using the templateview or even the formsviews, but I will consider in this answer what you are already using.

Since you need to manipulate various data coming from the form, the ideal would be to use the method POST instead of GET, get would be interesting for a query request, for example. You can see a summary here. Using POST, change your view to something like this:

class SolicitacaoReport(PermissionRequiredMixin, TemplateView):
    permission_required = 'administrativo_permissao'
    raise_exception = True
    template_name='administrativo/home.html'

    def post(self, request, *args, **kwargs):
        context = self.get_context_data()
        # Daqui para frente trate o contexto da forma que for necessario,
        # Exemplo: context['usuario'] => Nome do usuario

    def get_context_data(self, **kwargs):
        context = super(SolicitacaoReport, self).get_context_data(**kwargs)
        context['usuarios'] = User.objects.select_related().order_by('username')
        context['departamentos'] = Departamento.objects.select_related().order_by('nome_departamento')
        return context

See that the override of the method post, "capture" means the data contained in request, vc will have a dictionary with keys/values of the data sent by the form, Voce can then treat them on its own view or send it to another method, a lib, etc.

  • the first part worked I managed to get the form data, the problem I am now getting an error when redirecting to the function.

  • Attributeerror at /request/administrative/system/summary/filters/pdf 'Wsgirequest' Object has no attribute 'get'

  • What do you mean "redirect to the function"? if you have the data you can do whatever you want with it in the view itself. Edit the question and put the new version or ask another question with this new problem.

  • blz, I edited the question by putting the progress I’ve made so far.

  • 1

    got !!!!! was bobing in the if of the function was passing the parameter but did not pass where it stored... there will not even hahaha right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.