How can you conditionally return a JSON or HTML response from Django django-rest-framework's view?
djangorestframework
== 2.3.10My
settings.py
:
REST_FRAMEWORK = {
'PAGINATE_BY': 10,
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.TemplateHTMLRenderer',
'rest_framework.renderers.JSONRenderer',
)
}
- In my
url.py
, I added this as the last line:
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
- My view is something like:
def myview(request, id, format='json'):
if format == 'json' or format is None:
return Response(my_dict, status=status.HTTP_200_OK)
else:
return Response(my_dict, template_name='myhtml.html')
Everything works OK, if I explicitly use .html
or .json
format_prefix
in the url request. But it gives me the following error if I don't specify any format.
ImproperlyConfigured at /objects/29
Returned a template response with notemplate_name
attribute set on either the view or response
Request Method: GET
Request URL: localhost:8000/objects/29
Django Version: 1.7
Exception Type: ImproperlyConfigured
Exception Value: Returned a template response with notemplate_name
attribute set on either the view or response
Exception Location: D:\WORKSPACE\user...\lib\site-
I also tried:
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html', 'None'])
But it doesn't seem to work either.
Could someone please help? Thanks!