I am working my way through Django's tutorial but failing to display an API response using Django's render() function.
models.py
...
class MF_Version():
def get_MF_Version(self):
url = 'https://www.mediafire.com/api/1.5/system/get_version.php?response_format=json'
r = requests.get(url)
return r
...
views.py
...
def view_Version(request):
hr = HttpResponse(MF_Version().get_MF_Version())
return render(request, 'mediafire/version.html', {'hr': hr})
# return hr
...
version.html
{% if 1 %}
{{ hr }}
{% endif %}
Browser output:
<HttpResponse status_code=200, "text/html; charset=utf-8">
MefiaFire response:
{"response":{"action":"system\/get_version","current_api_version":"1.5","result":"Success"}}
If I comment out return render(...)
in the view.py file and replace it with return hr
, I do see the JSON response from MediaFire, but I cannot figure out how to access action
, current_api_version
and result
in the HTML template.
Any help is appreciated.
Use JsonResponse
, which is available since Django 1.7
from django.http import JsonResponse
def view_Version(request):
return JsonResponse(MF_Version().get_MF_Version())
You don't need render at all.
If you need render write it as follows (untested):
{% for x in hr %}
{{ x }}: {{ hr.x }}
{% endfor %}
and your python code will look like:
import json
from django.http import JsonResponse
def view_Version(request):
hr = JsonResponse(MF_Version().get_MF_Version())
return render(request, 'mediafire/version.html', {'hr': json.loads(hr)})