首页 > python > 通过get方法将数据发送到Django中的TemplateView

通过get方法将数据发送到Django中的TemplateView (Send data through get method to a TemplateView in Django)

2016-08-15 pythonajaxdjango

问题

openpyxl用来将查询集下载到.xlsx文件中,为此我需要使用TemplateView。我通过使用JQuery-Ajax调用TemplateView,我发送了一个我需要在查询集中用作参数的变量,但我不知道如何在TemplateView中使用该变量的值。

默认情况下openpyxl覆盖GET方法,使用:

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

我试图通过此代码获取变量:

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

使用该代码我收到此错误:

500: KeyError at /the_url/
'numbers'

在错误中显示:

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

其中number是GET我通过Ajax发送的变量的名称。

那么,我如何GET在TemplateView中获取变量值?

解决方法

您应该能够通过访问您的变量self.request.GET.get('number')get_context_data方法。

模板视图示例(Python3版本)

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)

问题

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?

解决方法

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)
相似信息