views:

249

answers:

2

So, Generic views are pretty cool, but what I'm interested in is something that's a generic template.

so for example, I can give it an object and it'll just tostring it for me.

or if I give it a list, it'll just iterate over the objects and tostring them as a ul (or tr, or whatever else it deems necessary).

for most uses you wouldn't need this. I just threw something together quickly for a friend (a bar stock app, if you must know), and I don't feel like writing templates.

+3  A: 

If there's a django model for it, you can just stick to django.contrib.admin or django.contrib.databrowse. If not, then you might manage by skipping the django template altogether. example:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)

But of course you wanted to avoid even writing that much, so instead of doing html, we can use plain text and the pprint module:

from django.http import HttpResponse
import datetime
from pprint import pformat

def current_datetime(request):
    now = datetime.datetime.now()
    return HttpResponse(pformat(now), mimetype="text/plain")

edit: Hmm... this seems like something a view decorator should handle:

from django.http import HttpResponse
import datetime
import pprint

def prettyprint(fun):
    return lambda request:HttpResponse(
            pprint.pformat(fun(request)), mimetype="text/plain")

@prettyprint
def current_datetime(request):
    return datetime.datetime.now()
TokenMacGuy
thats exactly what I wanted. that'll teach me to overcomplicate. thanks!
Oren Mazor
+1  A: 

I don't see you getting away from writing templates, especially if you would want to format it, even slightly.

However you can re-use basic templates, for e.g, create a generic object_list.html and object_detail.html

that will basically contain the information to loop over the object list and present it, and show the object detail. You could use these "Generic" templates across the entire app if need be.

Rasiel