Login

Load template from specific app

Author:
fabiomontefuscolo
Posted:
May 22, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

It's an update of snippet https://djangosnippets.org/snippets/1376/ to work with Django 1.8. With this piece of code, you can override admin templates without copy or symlink files. Just write your template and extend the target.

 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
import io
from os.path import dirname, join, abspath
from django.db.models import get_app
from django.template import TemplateDoesNotExist
from django.template.loaders.base import Loader as BaseLoader


class Loader(BaseLoader):
    is_usable = True

    def get_template_path(self, app_template_name, template_dirs=None):
        template_parts = app_template_name.split(":", 1)

        if len(template_parts) != 2:
            raise TemplateDoesNotExist()

        app_name, template_name = template_parts
        app_dir = dirname(get_app(app_name).__file__)
        template_dir = abspath(join(app_dir, 'templates'))

        return join(template_dir, template_name)

    def load_template_source(self, template_name, template_dirs=None):
        filepath = self.get_template_path(template_name, template_dirs)
        try:
            with io.open(filepath, encoding=self.engine.file_charset) as fp:
                return fp.read(), filepath
        except IOError:
            pass
        raise TemplateDoesNotExist(template_name)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 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.