views:

72

answers:

2

I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far:

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template.loader import render_to_string

def raw_response(template):
    def wrap(view):
        def response(request,*args,**kwargs):
            if request.method == "GET":
                try:
                    if request.GET['raw'] == "1":
                        render = HttpResponse(render_to_string(template,{}),content_type="text/plain")
                        return render
                except Exception:
                    render = render_to_response(template,{})
                    return render
        return response
    return wrap

Currently, the {} is there just as a place holder. Ultimately, I'd like to be able to pass a dict like this:

@raw_response('my_template_name.html')
def view_name(request):
  render({"x":42})

Any assistance is appreciated.

A: 

You just need to call view from within your decorator and use the context returned from that.

if request.method == "GET":
    context = view(*args, **kwargs)
    try:
        if request.GET['raw'] == "1":
            render = HttpResponse(
                         render_to_string(template, context),
                         content_type="text/plain"
                     )
            return render

and so on. Although I'm not sure what's supposed to happen if raw is not 1.

Daniel Roseman
Thank you! again, the context = view(*args, **kwargs) is what I was missing.
polera
A: 

Have your real view method return something sensible (a context dict in this case) and call it.

def raw_response(template):
    def wrap(view):
        def response(request, *args, **kwargs):
            context = view(request, *args, **kwargs)
            if request.method == 'GET' and request.GET.get('raw', '0') == '1':
                return HttpResponse(render_to_string(template, context),
                                    content_type='text/plain')
            # POST or not raw
            return render_to_response(template, context)
        return response
    return wrap

@raw_response('my_template_name.html')
def view_name(request):
    return {'x': 42}
insin
Perfect, thanks!
polera