append extra data to request.POST in django

Viewed 4080

I am working on a pdf show feature in Django, the user enters data in HTML form and can click on the Preview button to see the preview in pdf format

these are the lines in my views.py which return pdf as the response

pdf = render_to_pdf('new_pdf.html', params)
return HttpResponse(pdf, content_type='application/pdf')

here render_to_pdf() takes HTML template and normal python dictionary to embed data on html page and convert it to pdf

I am currently passing form POST data as params i.e. params = {'data':request.POST}

request.POST looks like this

<QueryDict: {'csrfmiddlewaretoken': ['some_random_string_here'], 'client_id': ['26'], 'note_no': ['5']}>

and some more fields...

now I can simply use {{data.client_id}} in my HTML to get the data

everything's working fine till now

but I need to supply some extra data to my params to show on pdf

I was wondering if there's a way I can append my extra variables in request.POST like

request.POST['credit_type'] = [credit_type]

but this is not a regular python dictionary and gives This QueryDict instance is immutable

is there any work-around for this??

or do I have to use the regular approach of appending key-value pairs to my params and then use them ?

2 Answers
if request.method == 'POST':
    updated_request = request.POST.copy()
    updated_request.update({'credit_type': [credit_type]})

You can try to unpack the request.POST dictionary and add your own key-value pairs. This way you keep the original dictionary intact.

new_dict = {**request.POST, 'custom_key': custom_val}
Related