英文:
KeyError at /x/x/ 'pk' django
问题
views.py
class MangaView(DetailView):
model = Manga
template_name = 'mangas/manga.html'
context_object_name = 'manga'
slug_field = 'manga_slug'
slug_url_kwarg = 'manga_slug'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
manga = get_object_or_404(Manga, id=self.kwargs['pk']) # error line
favorited = False
latered = False
...
return data
urls.py
urlpatterns = [
path('mangas/', MangasHomeView.as_view(), name='mangas-home'),
path('manga/<slug:manga_slug>/', MangaView.as_view(), name='manga'),
...
]
请注意,代码部分没有进行翻译。
英文:
I'm trying to get a DetailView's model's pk in a variable in the get_context_data but I keep getting the error KeyError at /x/x/ 'pk'.
views.py
class MangaView(DetailView):
model = Manga
template_name = 'mangas/manga.html'
context_object_name = 'manga'
slug_field = 'manga_slug'
slug_url_kwarg = 'manga_slug'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
manga = get_object_or_404(Manga, id=self.kwargs['pk']) # error line
favorited = False
latered = False
...
return data
urls.py
urlpatterns = [
path('mangas/', MangasHomeView.as_view(), name='mangas-home'),
path('manga/<slug:manga_slug>/', MangaView.as_view(), name='manga'),
...
]
答案1
得分: 2
你看到的错误是因为尝试通过self.kwargs
访问pk
值,而实际上你的视图正在使用slug
字段和slug URL参数。
尝试使用self.get_object()
,因为它会在DetailView
中为你提供当前实例,无论是pk
还是slug
,如下所示:
class MangaView(DetailView):
model = Manga
template_name = 'mangas/manga.html'
context_object_name = 'manga'
slug_field = 'manga_slug'
slug_url_kwarg = 'manga_slug'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
manga = self.get_object()
favorited = False
latered = False
...
return data
英文:
The error you are seeing is caused by trying to access the pk
value through self.kwargs
, when in fact your view is using a slug
field and slug URL parameter.
Try to use self.get_object()
as it gives you current instance in DetailView
whether it is pk
or slug
so:
class MangaView(DetailView):
model = Manga
template_name = 'mangas/manga.html'
context_object_name = 'manga'
slug_field = 'manga_slug'
slug_url_kwarg = 'manga_slug'
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
manga = self.get_object()
favorited = False
latered = False
...
return data
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论