Home > OS >  Passing data from post form to FileResponde view
Passing data from post form to FileResponde view

Time:05-18

I recently started using Django and I managed to create two views, one to submit a form and another to return a FileResponse, separately, they work fine.

Now, I need to integrate both, when the client submit the form, I want to redirect to the another view using the fields submitted at the previous form. How can I do that?

Here is my form view:

def submitForm(request):
    
    if 'report' in request.POST:
        
        date_start = request.POST.get('date_start')
        date_end = request.POST.get('date_end')
        state = request.POST.get('state')
    
    return render(request, 'comissao.html')

Here is my view that creates a pdf file

def createPdf(request):

    date_start = '20220301'
    date_end = '20220331'
    state = 'G00471'
    
    body = "some html"
    options = { 'quiet': '' }
    pdfkit.from_string(body, options=options)

    file = open('file.pdf', 'rb')
    
    return FileResponse(file)

As you can see, I need the information passed at my first view, to use at second view, I tried something like this, but I think I'm mistaking the concept,

return reverse('pdf', kwargs={'state':state, 'date_start':date_start, 'date_end':date_end})

CodePudding user response:

reverse() only returns the URL, but I think you rather want to do a redirect() to that view.

For passing the parameters you have several options:

  • GET parameters
  • Session
  • URL parameters

Let's use GET parameters, which I would suggest:

from urllib.parse import urlencode

...
def submitForm(request):
    ...
    response = redirect('pdf')
    params = { state' : state, 'date_start: date_start, 'date_end': date_end}
    response['Location']  = f'?{urlencode(params)}'
    return response

Then in your PDF view you need to parse the GET parameters:

def createPdf(request):
    date_start = request.GET.get("date_start")
    ...

Note that you may also need to convert your dates into string and back for the query, which I ignored here.

  • Related