'Keyerror at /' 在列表视图的查询集中传递带有主键的用户时
'Keyerror at /' when passing user with primary key in queryset for a listview
models.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)
views.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,请问有什么办法可以解决吗
提前致谢...!
self.kwargs
包含 URL 路径中的参数。所以在你的 urls.py
中,你应该定义如下内容:
# urls.py
from app.views import HomePageView
urlpatterns = [
path('<b><int:pk></b>/', HomePageView.as_view()),
]
然后您可以使用有效的主键访问该页面,例如 /14
如果 14
是 User
的有效主键。
如果您想使用登录用户,您应该使用self.request.user
:
# 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 the models.DateTimeField(default=timezone.now)
, since that will make the field non-editable, etc.
models.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)
views.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,请问有什么办法可以解决吗 提前致谢...!
self.kwargs
包含 URL 路径中的参数。所以在你的 urls.py
中,你应该定义如下内容:
# urls.py
from app.views import HomePageView
urlpatterns = [
path('<b><int:pk></b>/', HomePageView.as_view()),
]
然后您可以使用有效的主键访问该页面,例如 /14
如果 14
是 User
的有效主键。
如果您想使用登录用户,您应该使用self.request.user
:
# 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.