[Django]-Django generic templates

5👍

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

1👍

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

Leave a comment