在 webapp 中,要检索来自特定用户的所有对象,我使用的是用户 pk。但是为了使 url 更具可读性,我想使用用户名。问题出在 django 视图中,用户 pk 在 kwargs 中给出了正确的值,但是当我使用用户名时它显示错误。
这是我使用“用户名”作为 kwargs 的代码,即返回 keyerror,
视图.py
class UserAllQuestionView(generic.ListView):
model = Question
template_name = 'mechinpy/user_profile_question.html'
context_object_name = 'user_all_questions'
def get_queryset(self):
return Question.objects.filter(user=self.kwargs['username'])
网址.py
path('m/user/<str:slug>/questions/', views.UserAllQuestionView.as_view(), name='user_profile_question_all'),
html
<a href="{% url 'mechinpy:user_profile_question_all' user.username %}">All User Questions</a>
追溯:
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\list.py" in get
142. self.object_list = self.get_queryset()
File "C:\Users\Bidhan\Desktop\Startup\mysite\mechinpy\views.py" in get_queryset
454. return Question.objects.filter(user=self.kwargs['username'])
Exception Type: KeyError at /m/user/bidhan/questions/
Exception Value: 'username'