Posted By

chrisaiv on 01/03/12


Tagged

django


Versions (?)

Django: 3 ways to serve templates in views.py


 / Published in: Django
 

There are so many ways to serve templates within views.py that sometimes it's hard to get a handle on which is ideal for a project. This snippet does not attempt to explain every possible way to serve a template, simply a few I've found helpful organized from low-level (more code) to high-level (less code)

  1. #Things to remember
  2. #django.core.context_processors.auth contains:
  3. #User instance representing the current logged-in user
  4. #Messages tied to a user
  5. #Perms represents permissions the current logged-in user has
  6. #django.core.context_processors.request
  7. #
  8.  
  9. from django.shortcuts import render_to_response, get_object_or_404
  10. from django.template import Context, RequestContext, loader
  11. from django.template.loader import get_template
  12.  
  13. #
  14. #Lowest Level
  15. #
  16. #Manually loading a template, constructing context, rendering templates
  17. #Does not take advantage of render_to_response()
  18. def view_lowest(request):
  19. t = loader.get_template("name_of_template.html")
  20. c = Context({
  21. "var1": var1,
  22. "var2": var2,
  23. "var3": var3
  24. })
  25. return t.render(c)
  26. #
  27. #Low Level
  28. #
  29. def custom_processor(request):
  30. return {
  31. "var1": var1,
  32. "var2": var2,
  33. "var3": var3
  34. }
  35.  
  36. def view_lower(request):
  37. t = loader.get_template("name_of_template.html")
  38. c = RequestContext(request, {"unique_message": "Specific to a template"},
  39. processors=[custom_processor])
  40. return t.render(c)
  41.  
  42. #
  43. #Normal Level
  44. #
  45. def custom_processor(request):
  46. return {
  47. "var1": var1,
  48. "var2": var2,
  49. "var3": var3
  50. }
  51.  
  52. def view_normal(request):
  53. return render_to_response("name_of_template.html", {"unique_message": "Specific to a template"},
  54. context_instance=RequestContext(request, processors=[custom_processor]))
  55.  
  56. def view_normal2(request):
  57. return render_to_response("name_of_template.html", {"unique_message": "Specific to a template2"},
  58. context_instance=RequestContext(request, processors=[custom_processor]))

Report this snippet  

You need to login to post a comment.