下面的视图打印特定用户完成的所有帖子的列表。用户是从URL获取的参数,并且工作正常。
如何提取** kwarg->'username'并将其作为变量显示在模板上?
已经尝试了代码中注释掉的内容。
views.py
class AuthorPostIndexView(ListView):
model = Person
template_name ='authorpostindex.html'
context_object_name = 'author_post'
#1)
#date=request.GET.get('username','') -> wrong as varibales in classes
#is not possible?
#-> this works fine:
def get_queryset(self):
username = self.kwargs['username']
queryset = Person.objects.get(username=username).post.all()
return queryset, (username,'')
#-> attempts to extract username kwarg:
#2)
# def get_context_data(self, **kwargs):
# context = super(AuthorPostIndexView, self).get_context_data(**kwargs)
# context['username'] = self.username
# return context
#3)
# @property
# def username(self):
# return self.kwargs['username']
预期结果
template.html
<h1>{{username}}</h1> -> username from the URL should be displayed
错误消息:
ps。咨询后仍然无法正常工作:
解决方案看起来很相似,但是我认为将kwarg参数排除在方法之外是有问题的。另外,我对放置在模板中的内容失去了信心。
我可以在函数中返回两个参数吗?
class AuthorPostIndexView(ListView):
model = Post
template_name ='authorpostindex.html'
context_object_name = 'author_post'
def get_queryset(self):
queryset = super().get_queryset()
username = self.kwargs['username']
return (queryset.filter(authors__username=username),username)
或者在建议的解决方案之一中,我向视图添加了方法
def get_context_data(self, **kwargs):
context = super(AuthorPostIndexView, self).get_context_data(**kwargs)
context['username'] = self.kwargs['username']
return context
...然后是模板
authorpostindex.html
{{context}}
or
{{username}}
or
{{context.username}}
那不行
答案 0 :(得分:2)
尝试
def get_context_data(self, **kwargs):
context = super(AuthorPostIndexView, self).get_context_data(**kwargs)
context['username'] = self.kwargs['username']
# or
context['username'] = self.request.GET.get('username', None)
return context
希望有帮助