我将通过在我的 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/