这个问题也受到文档 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].
关于python - 在 django urls.py 中访问请求对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62899042/