python - 在 django urls.py 中访问请求对象

这个问题也受到文档 here 的启发。 .

我在 Django 中使用通用 View (ListView) 以列出当前登录用户提出的所有问题。我很想在不在 views.py 中创建 View 的情况下执行此操作。所以在 urls.py 中我添加了如下路径:

urlpatterns += [
    path('myqn/', login_required(views.ListView.as_view(model=models.Question, queryset=models.Question.objects.filter(user__id=request.user.id), template_name='testapp/question_list.html', context_object_name='questions')), name='myqn'),
]

它给了我:

NameError: name 'request' is not defined

我知道。因为,请求对象由 URLConf 传递给 View 类/函数。那么,有没有办法,我可以在此范围内访问 user.id。

PS:如果我替换 user__id=9,代码就可以工作。它列出了用户 9 提出的所有问题。 :)

最佳答案

您通常通过覆盖 ListView子类 中的get_queryset 方法来完成此操作。所以你可以创建一个 View :

# app/views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.list import ListView
from app.models import Question

class QuestionListView(LoginRequiredMixin, ListView):
    model = Question
    template_name='testapp/question_list.html'
    context_object_name='questions'

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            <b>user_id=self.request.user.id</b>
        )

然后在 urls.py 中使用 QuestionListView

# app/urls.py

from django.urls import path
from app.views import QuestionListView

urlpatterns += [
    path('myqn/', <b>QuestionListView.as_view()</b>, name='myqn'),
]

您可以定义函数或 lambda 表达式:

import inspect

def <b>custom_queryset</b>(*args, **kwargs):
    self = inspect.currentframe().f_back.f_locals['self']
    return Question.objects.filter(
        user_id=self.request.user.id
    )

urlpatterns += [
    path('myqn/', QuestionListView.as_view(<b>get_queryset=custom_queryset</b>), name='myqn'),
]

但这不是一个好主意。首先,它会检查调用堆栈,如果稍后更改 ListView,它可能不再工作。此外,此 ListView 不会检查用户是否已登录。我们不能使用方法解析顺序 (MRO) 来调用 super() 方法。


Note: You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc].

https://stackoverflow.com/questions/62899042/

相关文章:

azure-devops - 在 YAML 部署作业中部署后检查应用程序运行状况端点的最佳方法?

java - 在 Java 中不使用类创建对象

python-3.x - 可以将我的临时文件放入我的应用程序中的 tmp/目录吗?

python - 为什么我会收到 KeyError : 0

php - 如何在 WooCommerce 中获取产品特定的元数据

css - 对齐元素 : center not working in flexbox

r - 为什么同一个查询使用 dplyr 在不同的 R session 上返回不同的结果?

amazon-web-services - 我们可以在 Route 53 AWS DNS 服务中创建

html - 在 flex 中将 div 的内容右对齐

azure - 卡夫卡与 SignalR