Django - urls.py 中的访问会话

发布于 2024-11-23 22:02:34 字数 404 浏览 2 评论 0原文

我试图使用 ListView 来避免为应该非常简单的页面创建视图。 基本上我想列出一组与当前用户相关的对象,但是我不确定如何从 urls.py 中访问会话值。

我所拥有的看起来像这样:

 (r'^myrecords/$', ListView.as_view(
        queryset=Record.objects.filter(CURRENT LOGGED IN USER),
        context_object_name='record_list',
        template_name='records.html')),

我需要做什么?

还有什么方法可以应用 login_required 装饰器吗?

任何建议将不胜感激。

谢谢。

I'm trying to use a ListView to avoid creating a view for what should be quite a simple page.
Basically I want to list a set of objects related to the current user, however I'm not sure how to access the session values from within the urls.py.

What I have looks something like this:

 (r'^myrecords/

What do I need to do?

Also is there any way to apply the login_required decorator to this?

Any advice would be greatly appreciated.

Thanks.

, ListView.as_view( queryset=Record.objects.filter(CURRENT LOGGED IN USER), context_object_name='record_list', template_name='records.html')),

What do I need to do?

Also is there any way to apply the login_required decorator to this?

Any advice would be greatly appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千秋岁 2024-11-30 22:02:34

请参阅动态过滤上的文档。

您应该子类化 ListView 并重写 get_queryset 方法。调用基于类的视图时,self 会填充当前请求 (self.request) 以及从 URL 捕获的任何内容 (self.argsself.kwargs)。

from django.views.generic import ListView
from myapp.models import Record

class MyRecordsListView(ListView):
    context_object_name = 'record_list'
    template_name = 'records.html',

    def get_queryset(self):
        return Record.objects.filter(user=self.request.user)

还有装饰基于类的文档视图。基本上,您可以在 urls.py 中装饰 as_view 的结果:

(r'^myrecords/
, login_required(MyRecordsListView.as_view())),

See the docs on dynamic filtering.

You should subclass ListView and override the get_queryset method. When the class-based view is called, self is populated with the current request (self.request) as well as anything captured from the URL (self.args, self.kwargs).

from django.views.generic import ListView
from myapp.models import Record

class MyRecordsListView(ListView):
    context_object_name = 'record_list'
    template_name = 'records.html',

    def get_queryset(self):
        return Record.objects.filter(user=self.request.user)

There's also documentation for decorating class-based views. Basically you can just decorate the result of as_view in your urls.py:

(r'^myrecords/
, login_required(MyRecordsListView.as_view())),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文