python - Django:在基于类的通用 View ListView 中访问 HttpRequest

标签 python django django-class-based-views

我将通过在我的 views.py 中对 ListView 进行子类化来实现一个基于自定义类的通用 View 。我的问题是如何能够访问我的子类中的请求(HttpRequest 对象)参数?我所涉及的 HttpRequest 对象是 views.py 中所有函数的默认请求参数。例子:

def search(request):

更清楚地说,这是我迄今为止尝试过的:

** View .py
class CustomListView(ListView):
    temp = ""

    def get(self, request, *args, **kwargs):
        self.temp = request.GET.get('temp')
        return super(CustomListView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(CustomListView, self).get_context_data(**kwargs)
        context['temp'] = self.temp
        return context

**网址.py
url(r'^temp/$, CustomListView.as_view(queryset=Document.objects.all()[:1],template_name="temp.html")),

**temp.html
{% extends 'base.html' %}
{% block content %}
<h2>{{ temp }}
{% endblock %}

但是当我运行服务器并访问/temp/(temp.html) 时,我看到的只是“无”。所以意思是, 'temp' is ""或 'temp' 根本没有被创建。

任何想法都非常感谢。谢谢!

最佳答案

通常,您可以在尚未传递请求的 CBV 方法中使用 self.request。

所以你可以使用

    context['temp'] = self.request.GET.get('temp') 

在您的 get_context_data方法,然后删除您的 get完全覆盖方法。

关于python - Django:在基于类的通用 View ListView 中访问 HttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25381870/

相关文章:

python - 使用 python 实现基于 Web 的桌面应用程序

python - 服务器拓扑帮助 - Django 和 Twisted 的可能性?

带有 GET 参数的基于 Django 类的 View

python - 保持 Python 脚本运行的简单方法?

Python 3 在划分两个大数时给出错误的输出?

python - 将标量转换为 numpy 数组的有效方法

django - 'NoneType' 类型的对象在 django ClassBased ListView 中没有 len()

python - 部分被遮挡的物体(平行线)检测

python - 在 Django 请求 header 中访问用户名和密码返回 None

python - 基于类的 View 中的可选 url 参数