问题描述
我发现了一个类似的问题,但它是针对 Django 1.5 的,我认为它对我不起作用。
class SearchedPostListView(ListView):
model = Post
template_name = 'blog/search.html' # <app>/<model>_<viewtype>.html
paginate_by = 2
context_object_name = 'posts'
def get_context_data(self,*args,**kwargs):
context = super(SearchedPostListView,self).get_context_data(*args,**kwargs)
query = self.kwargs.get('q')
context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query))
context['categories'] = Categories.objects.all
return context
这是我的代码。我正在尝试搜索我网站上的所有帖子,并显示标题中包含查询的所有帖子。
因此,如果我输入 URL localhost:8000/search?q=foo
,那么它必须向我显示标题中包含单词 foo
的帖子。
但我无法访问 GET 参数。如何在 Django 3.2 中访问 GET 参数?
解决方法
使用 query = self.request.GET.get('q')
代替 query = self.kwargs.get('q')
。
class SearchedPostListView(ListView):
model = Post
template_name = 'blog/search.html' # /_.html
paginate_by = 2
context_object_name = 'posts'
def get_context_data(self,*args,**kwargs):
context = super(SearchedPostListView,self).get_context_data(*args,**kwargs)
query = self.request.GET.get('q')
context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query))
context['categories'] = Categories.objects.all
return context