elG elG - 3 months ago 16
Python Question

Send data through get method to a TemplateView in Django

I am using

openpyxl
to download querysets into .xlsx files, and for that I need to use a TemplateView. I am calling the TemplateView by using JQuery-Ajax, I send a single variable that I need to use as a parameter in my queryset, but I don't know how to use the value of that variable in the TemplateView.

By default
openpyxl
overrides
GET
method, using this:

def get(self, request, *args, **kwargs):


And I have tried to get the variable by this code:

context = self.get_context_data()
valor=context["number"]


With that code I'm getting this error:

500: KeyError at /the_url/
'numbers'


In the error show this:

Request URL: http://127.0.0.1:8000/the_url/?number=34


Request information:
GET:
number = '34'

POST: No POST data

FILES: No FILES data


Where number is the name of the
GET
variable that I'm sending trough Ajax.

So, how can I get the
GET
variable value in a TemplateView?

Answer

You should be able to access your variable via self.request.GET.get('number') in the get_context_data method.

Example of template view (Python3 version)

class MyTemplateView(TemplateView):
    template_name = 'path/to/tempplate.html'

    def get_context_data(self, **kwargs):
        valor = self.request.GET.get('number')
        return super().get_context_data(**kwargs)