在 Django 3.2 的 class-base 视图中获取 GET url 参数
Get GET url parameters in class-base views for Django 3.2
我发现了一个类似的问题,但它是针对 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)
<b>query = self.request.GET.get('q')</b>
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</pre>
我发现了一个类似的问题,但它是针对 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)
<b>query = self.request.GET.get('q')</b>
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</pre>