python - 'Keyerror at /' 在列表视图的查询集中使用主键传递用户时
问题描述
模型.py
class Notes(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
视图.py
class HomepageView(ListView):
model = Notes
template_name = "home.html"
def get_queryset(self):
return Notes.objects.filter(Q(author=self.kwargs['pk']))
它指出 pk 有 KeyError,有没有办法摆脱它提前谢谢......!
解决方案
The self.kwargs
contains the parameters, that are in the URL path. So in your urls.py
, you should define shomething like:
# urls.py
from app.views import HomePageView
urlpatterns = [
path('<int:pk>/', HomePageView.as_view()),
]
Then you can visit the page, with a valid primary key, so for example /14
if 14
is a valid primary key for a User
.
If you want to use the logged in user instead, you should use self.request.user
instead:
# in case you want to use the logged in user
django.views.generic.list import ListView
from django.contrib.auth.mixins import LoginRequiredMixin
class HomepageView(LoginRequired, ListView):
model = Notes
template_name = 'home.html'
def get_queryset(self):
return Notes.objects.filter(author=self.request.user)
Note: it might be better to use
get_user_model
[Django-doc] to point to the user model, since if you later change the user model, altering the foreign keys will be easier.
Note: You might want to consider using a
DateTimeField(auto_now_add=True)
instead of themodels.DateTimeField(default=timezone.now)
, since that will make the field non-editable, etc.
推荐阅读
- testing - Katare DSL - 无法读取功能文件中的 .prn 文件,它会引发错误“忽略动态表达式,未评估到列表”
- django - PasswordChangeView 未重定向到 PasswordChangeDoneView(或更改密码)
- html - 在 HTML 表格中切换子菜单列表
- python - 如何运行命令的多个实例并能够在 discord.py 中取消某个实例
- reactjs - react-chartjs-2 如何在折线图中设置多个背景级别
- html5-video - 视频/mp2t 浏览器直播支持
- apache - Appache - 由 br (brotli) 压缩的下载文件出现问题
- python - RobotFramework - 将查询结果与另一个文件的结果进行比较
- sql - 基于值格式的条件连接
- android - 从 android viewmodel 调用 notifyDataSetChanged()