我想在我的模板上呈现所有对象的列表,它们的作者是当前登录的用户。我将当前用户的用户名传递给 url.py
:
<a href="{% url 'myscenarios' user.username %}">My List</a>
我的 urls.py:
path('myscenarios/<str:username>/', MyScenarioListView.as_view(), name='myscenarios'),
我的问题是如何在 views.py
中构建查询集以及在我的 html 中的模板 block 中输入什么?
class MyScenarioListView(LoginRequiredMixin, ListView):
model = Scenario
template_name = 'testmanager/myscenarios.html'
context_object_name = 'myscenarios'
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Scenario.objects.filter(scenarioAuthor = user).order_by('-date_posted')
我应该在我的 myscenarios.html
文件中输入什么代码?
最佳答案
I want to render list of all objects on my template, which their author is current logged user.
然后您应该不对路径中的用户进行编码,因为“黑客”随后可以简单地更改 URL 以查看属于不同用户的项目。
你可以在这里使用self.request.user
。因此路径看起来像:
path('myscenarios/', MyScenarioListView.as_view(), name='myscenarios'),
在 View 中,我们使用:
class MyScenarioListView(LoginRequiredMixin, ListView):
model = Scenario
template_name = 'testmanager/myscenarios.html'
context_object_name = 'myscenarios'
def get_queryset(self):
return Scenario.objects.filter(
scenarioAuthor=<b>self.request.user</b>
).order_by('-date_posted')
它会将 Scenarios
作为 myscenarios
传递给模板,因此您可以使用以下方式呈现它:
{% for scenario in myscenarios %}
{{ scenario }}
{% endfor %}
关于python - Django ListView 中当前用户对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408167/