Request.GET 在自定义 HTML Django Rest Framework 渲染器模板中不可用
Posted
技术标签:
【中文标题】Request.GET 在自定义 HTML Django Rest Framework 渲染器模板中不可用【英文标题】:Request.GET not available in custom HTML Django Rest Framework renderer template 【发布时间】:2021-04-08 12:26:24 【问题描述】:我有这个使用 Django Rest Framework 的自定义 html 渲染器:
from rest_framework.renderers import TemplateHTMLRenderer
class CustomHTMLRenderer(TemplateHTMLRenderer):
def
renderer_context = renderer_context or
view = renderer_context['view']
request = renderer_context['request']
response = renderer_context['response']
if response.exception:
template = self.get_exception_template(response)
else:
template_names = self.get_template_names(response, view)
template = self.resolve_template(template_names)
context = self.get_template_context('content': data, renderer_context)
return template.render(context)
这是我对在我的 Solr 服务器上执行的搜索的看法:
import os
from django.conf import settings
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from rest_framework.pagination import LimitOffsetPagination
import collections
from collections import OrderedDict
from rest_framework.settings import api_settings
import scorched
from scorched.strings import DismaxString
from bassculture.renderers.custom_html_renderer import CustomHTMLRenderer
class SearchResultsPagination(LimitOffsetPagination):
def get_paginated_response(self, data):
self.solr_response = data['solr_response']
self.offset = self.solr_response.result.start
self.limit = len(data['records'])
self.count = self.solr_response.result.numFound
self.request = data['request']
resp = Response(OrderedDict(
'count': self.count,
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'results': data['records'],
'facets': self.solr_response.facet_counts.facet_fields,
'params': self.solr_response.params,
'highlighting': self.solr_response.highlighting,
'limit': self.limit,
))
return resp
class SearchViewHTMLRenderer(CustomHTMLRenderer):
template_name = "search/search.html"
class SearchView(GenericAPIView):
renderer_classes = [JSONRenderer, SearchViewHTMLRenderer]
pagination_class = SearchResultsPagination
def get(self, request, *args, **kwargs):
querydict = request.GET
offset = querydict.get('offset', 0)
fcq =
for f in settings.SEARCH_FACETS:
if querydict.get(f, None):
fcq[f] = querydict.get(f)
fq =
if querydict.get('fq'):
fq = querydict.get('fq')
else:
fq = '*'
si = scorched.SolrInterface(settings.SOLR_SERVER)
response = si.query(DismaxString(querydict.get('q'))).filter(**fcq).filter(fq).highlight('*', fragsize=10).paginate(start=int(offset), rows=api_settings.PAGE_SIZE).facet_by(fields=settings.SEARCH_FACETS, mincount=1).execute()
for d in response:
d['highlighted_string'] = response.highlighting[d['id']]
results_list = response
records = []
for result in response:
type = result['type']
pk = result['id'].split('_')[1]
result['url'] = request.build_absolute_uri(os.path.join('/fiddle/', type, pk))
records.append(result)
d =
'records': records,
'solr_response': response,
'request': request,
resp = self.get_paginated_response(d)
return resp
结果的 JSON 正在通过。实际上,如果我将 renderer_classes 更改为
renderer_classes = [JSONRenderer]
浏览器显示原始 JSON。所以,我想,我的 HTML 渲染器有问题。会是什么呢? HTML 渲染器在我网站的其他页面中工作得很好(我不必处理 JSON 数据)。
Django==3.1.4 djangorestframework==3.12.2
更新
我发现问题在于我无法从我的模板访问我的请求参数。我有一个
% if request.GET.q %
Results....
% endif %
这使结果页面无效。
如何访问我的请求参数?我的设置中有'django.template.context_processors.request'
。
【问题讨论】:
【参考方案1】:我忘记在我的回复template.render
调用中添加request=request
:
return template.render(context, request=request)
【讨论】:
以上是关于Request.GET 在自定义 HTML Django Rest Framework 渲染器模板中不可用的主要内容,如果未能解决你的问题,请参考以下文章