开发者

django generic templates

So, Generic views are pretty cool, but what I'm interested i开发者_如何学运维n 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.


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()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜