Last active
July 10, 2020 01:13
-
-
Save dminkovsky/4696499 to your computer and use it in GitHub Desktop.
Django: Generate corresponding JSON and rendered template (HTML) views from the same data dictionary.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
from django.utils.functional import wraps | |
from django.template.context import RequestContext | |
from django.template.loader import get_template | |
from django.utils import simplejson as json | |
def dict_to_template_view(**template_args): | |
""" | |
Takes a function that returns a dict and decorates it into a template-rendering view | |
""" | |
template_name = template_args.pop('template_name') | |
response_class = template_args.pop('response_class', HttpResponse) | |
def outer(func): | |
@wraps(func) | |
def inner(request, *args, **kwargs): | |
dict = func(request, *args, **kwargs) | |
context = RequestContext(request, dict) | |
template = get_template(template_name) | |
return response_class(template.render(context)) | |
return inner | |
return outer | |
def dict_to_json_view(**json_args): | |
""" | |
Takes a function that returns a dict and decorates it into a JSON-producing view | |
""" | |
indent = json_args.pop('indent', 4) | |
def outer(func): | |
@wraps(func) | |
def inner(request, *args, **kwargs): | |
dict = func(request, *args, **kwargs) | |
if not dict: | |
dict = {} | |
return HttpResponse(json.dumps(dict, indent=indent, **json_args), mimetype='application/json') | |
return inner | |
return outer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dict_to_view import dict_to_template_view, dict_to_json_view | |
from diagnose.models import BodyPart | |
def body_parts_list_dict(request): | |
""" | |
Returns a dictionary of root-level body parts | |
""" | |
body_parts = BodyPart.objects.filter(depth=1) | |
return { | |
'count' : body_parts.count(), | |
'body_parts' : [dict(name=body_part.name, id=body_part.id) for body_part in body_parts] | |
} | |
@dict_to_template_view(template_name='body_parts/list.html') | |
def body_part_list_as_html(request): | |
""" | |
A list view of body parts as HTML | |
""" | |
return body_parts_list_dict(request) | |
@dict_to_json_view(indent=2) | |
def body_part_list_as_json(request): | |
""" | |
A list view of body parts as JSON | |
""" | |
return body_parts_list_dict(request) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment