如何从Django中的urls.py访问HttpRequest [英] How to access HttpRequest from urls.py in Django
本文介绍了如何从Django中的urls.py访问HttpRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我想使用一个通用的视图来根据用户名列出对象。现在的问题是,我该怎么做,如下所示:
Basically I want to use a generic view that lists objects based on a username. Now, the question is, how do I do something like:
(r'^resources/$',
ListView.as_view(
queryset=Resources.objects.filter(user=request.user.username),
...
)
)
我找不到一种方法来访问HttpRequest(请求)对象,但是...或者我需要使用我自己的视图做所有的对象选择?
I couldn't find a way to access the HttpRequest (request) object though... Or do I need to use my own views and do all object selection there?
推荐答案
如果你真的想直接混淆你的URLconf,你可以这样做: p>
If you really want to clutter your URLconf directly, you can do it like so:
(r'^resources/$',
lambda request: ListView.as_view(queryset=Resources.objects.filter(user=request.user.username), ...)(request)
)
或者通过子视图来访问请求:
Or access the request by subclassing the view:
class MyListView(ListView):
def dispatch(self, request, *args, **kwargs):
self.queryset = Resources.objects.filter(user = request.user.username)
return super(MyListView, self).dispatch(request, *args, **kwargs)
这篇关于如何从Django中的urls.py访问HttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文