Login

Load Template from App

Author:
mikob
Posted:
December 1, 2013
Language:
Python
Version:
1.6
Score:
0 (after 0 ratings)

Updated a similar snippet by "King" to work with Django 1.6. This is especially useful for overriding the admin templates without having to symlink or copy them into your project. For example {% extends "admin:base.html" %} would extend the admin page base.html.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from os.path import dirname, join, abspath, isdir
 
from django.template.loader import BaseLoader
from django.db.models import get_app
from django.core.exceptions import ImproperlyConfigured
from django.template import TemplateDoesNotExist
from django.conf import settings
from django.utils._os import safe_join
 
class Loader(BaseLoader):
    is_usable = True
 
    def get_template_sources(self, template_name, template_dirs=None):
        app_name, template_name = template_name.split(":", 1)
        try:
            template_dir = abspath(safe_join(dirname(get_app(app_name).__file__), 'templates'))
        except ImproperlyConfigured:
            raise TemplateDoesNotExist()
        
        return template_name, template_dir
     
    def load_template_source(self, template_name, template_dirs=None):
        """ 
        Template loader that only serves templates from specific app's template directory.
     
        Works for template_names in format app_label:some/template/name.html
        """
        if ":" not in template_name:
            raise TemplateDoesNotExist()
     
        template_name, template_dir = self.get_template_sources(template_name)
     
        if not isdir(template_dir):
            raise TemplateDoesNotExist()
        
        filepath = safe_join(template_dir, template_name)
        with open(filepath, 'rb') as fp:
            return (fp.read().decode(settings.FILE_CHARSET), filepath)

     
    load_template_source.is_usable = True

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.