def personal_search(request): """ The user can search any item within his own collections and can search **only shared items** of other users TODO: Build a hash table to store item_id in the result of user_item to reduce time from O(n^2) to O(n) Reference: http://docs.haystacksearch.org/dev/searchqueryset_api.html#field-lookups """ #Two parameters to tune RESULTS_PER_PAGE = 10 load_all = False query = request.GET['q'].strip() #Heystack only accepts key name as 'q' user_id = int(request.GET['pid']) if query == '': sqs = EmptySearchQuerySet() else: searchqueryset = SearchQuerySet() if user_id == request.user.pk: pronoun = '我' own_items = User_Item.objects.filter(user__pk=request.user.pk) else: pronoun = Profile.objects.get(pk=user_id).name own_items = User_Item.objects.filter(user__pk=user_id).exclude(status=1) own_items_ids = [] for oi in own_items: own_items_ids.append(int(oi.item_id)) sqs = searchqueryset.auto_query(query).filter(primary_key__in=own_items_ids) if load_all: sqs = sqs.load_all() paginator = Paginator(sqs, RESULTS_PER_PAGE) try: page = paginator.page(request.GET.get('page', 1)) feeds_id = '' for result in page.object_list: feeds_id += str(result.object.id) + ',' feeds_id = feeds_id[:-1] topics_of_item_dict = get_topics_of_item(feeds_id, request.user.pk) friends_of_item_dict = get_friends_of_item(feeds_id, request.user.pk) user_item_status_dict = get_user_items(feeds_id, request.user.pk) except InvalidPage: raise Http404 context = { 'query': query, 'page': page, 'page_type':'search', 'topics_of_item_dict':topics_of_item_dict, 'friends_of_item_dict':friends_of_item_dict, 'user_item_status_dict':user_item_status_dict, 'paginator': paginator, 'suggestion': None, 'pronoun': pronoun, 'num_results': len(sqs), 'user_id': user_id } from django.template import add_to_builtins add_to_builtins('haystack.templatetags.highlight') return render_to_response('main/search/personal_search_results.html', context, context_instance=RequestContext(request))
def extra_builtins(): extras = ( 'qwert.templatetags.expr', 'qwert.templatetags.truncateletters', ) for extra in extras: add_to_builtins(extra)
def django_version_handling(): # Load up our own internal csrf_token in case they are using 1.1 pre 1.1.2 if django.VERSION[0] == 1 and django.VERSION[1] < 2: # We are in the 1.x series less than 1.2 if django.VERSION[1] == 1 and django.VERSION[2] < 2: add_to_builtins("formunculous.templatetags.csrf_backport")
def load_templatetags(): """http://www.djangosnippets.org/snippets/342/ """ from django.conf import settings from django.template import add_to_builtins # This is important: If the function is called early, and some of the custom # template tags use superclasses of django template tags, or otherwise cause # the following situation to happen, it is possible that circular imports # cause problems: # If any of those superclasses import django.template.loader (for example, # django.template.loader_tags does this), it will immediately try to register # some builtins, possibly including some of the superclasses the custom template # uses. This will then fail because the importing of the modules that contain # those classes is already in progress (but not yet complete), which means that # usually the module's register object does not yet exist. # In other words: # {custom-templatetag-module} -> # {django-templatetag-module} -> # django.template.loader -> # add_to_builtins(django-templatetag-module) # <-- django-templatetag-module.register does not yet exist # It is therefor imperative that django.template.loader gets imported *before* # any of the templatetags it registers. import django.template.loader try: for lib in settings.TEMPLATE_TAGS: add_to_builtins(lib) except AttributeError: pass
def __init__(self, request, response): self.__lang_map = {} for key, lang_list in LANG_MAP.iteritems(): self.__lang_map[key] = key for lang in lang_list: self.__lang_map[lang] = key settings.SETTINGS_MODULE = 'conf' if not template.libraries.get('lib.template_library', None): template.add_to_builtins('lib.template_library') super(self.__class__, self).__init__(request, response)
def test_templatetags(): add_to_builtins('django_tables.app.templatetags.tables') # [bug] set url param tag handles an order_by tuple with multiple columns class MyTable(tables.MemoryTable): f1 = tables.Column() f2 = tables.Column() t = Template('{% set_url_param x=table.order_by %}') table = MyTable([], order_by=('f1', 'f2')) assert t.render(Context({'request': HttpRequest(), 'table': table})) == '?x=f1%2Cf2'
def toggle(self, obj): """ Generates HTML to toggle comment approvement column """ label = _('Blame') if obj.is_approved else _('Approve') add_to_builtins('django.templatetags.i18n') tpl = '<a class="approve-comment-button" href="' tpl += '{% url admin:periodics_comment_toggle comment.id %}">' tpl += '{{ label }}</a>' return Template(tpl).render(Context({'comment': obj, 'label':label}))
def ban(self, obj): """ Generates HTML for 'Ban author' column """ label = _('Ban IP') add_to_builtins('django.templatetags.i18n') tpl = '<a class="ban-ip-button" href="' tpl += '{% url admin:periodics_ban_toggle comment.ip_address %}">' tpl += '{{ label }}</a>' return Template(tpl).render(Context({'comment': obj, 'label':label}))
def test_url_tag_override(self): # we should be setting HOST_OVERRIDE_URL_TAG to True # but that doesn't really work since that setting is read only # on import time for Django < 1.7 and on setup time for >= 1.7 # so we have to fake it by manually setting the stage from django.template import add_to_builtins add_to_builtins('django_hosts.templatetags.hosts_override') self.assertRender("{% url 'simple-direct' host 'www' %}", '//www.example.com/simple/') self.assertRender( "{% url 'simple-direct' host 'www' as " "simple_direct_url %}{{ simple_direct_url }}", '//www.example.com/simple/')
def search(request): """ Modification/Combination based on two haystack classes: 1,haystack/views/SearchView 2,haystack/forms/SearchForm/search() Reference: #. http://docs.haystacksearch.org/dev/ #. http://lucene.apache.org/solr/tutorial.html """ #Two parameters to tune RESULTS_PER_PAGE = 10 load_all = False query = request.GET['q'].strip() #Heystack only accepts key name as 'q' if query == '': sqs = EmptySearchQuerySet() else: searchqueryset = SearchQuerySet() sqs = searchqueryset.auto_query(query) #The default auto_query method has been modified to use OR instead of AND if load_all: sqs = sqs.load_all() paginator = Paginator(sqs, RESULTS_PER_PAGE) try: page = paginator.page(request.GET.get('page', 1)) feeds_id = '' for result in page.object_list: feeds_id += str(result.object.id) + ',' #If an item is deleted and not reindexed, then error feeds_id = feeds_id[:-1] topics_of_item_dict = get_topics_of_item(feeds_id, request.user.pk) friends_of_item_dict = get_friends_of_item(feeds_id, request.user.pk) user_item_status_dict = get_user_items(feeds_id, request.user.pk) except InvalidPage: raise Http404 context = { 'query': query, 'page': page, 'page_type':'search', 'topics_of_item_dict':topics_of_item_dict, 'friends_of_item_dict':friends_of_item_dict, 'user_item_status_dict':user_item_status_dict, 'paginator': paginator, 'suggestion': None, 'num_results': len(sqs), } from django.template import add_to_builtins add_to_builtins('haystack.templatetags.highlight') #Changed haystack.utils.Highlighter.highliht to not use window return render_to_response('main/search/web_search_results.html', context, context_instance=RequestContext(request))
def wrapped(*args, **kwargs): # Clean out default libraries # Note: template.builtins is merely a convenience import, # we have to work with template.base.builtins for this to # work right. template.base.builtins, default_libs = [], template.base.builtins try: # Construct new builtin with only whitelisted tags/filters whitelist = template.Library() for lib in default_libs: for tag in lib.tags: if tag in tags: whitelist.tags[tag] = lib.tags[tag] for filter in lib.filters: if filter in filters: whitelist.filters[filter] = lib.filters[filter] # Install whitelist library and extras as builtins template.base.builtins.append(whitelist) [template.add_to_builtins(e) for e in extra] return func(*args, **kwargs) finally: # Restore the builtins to their former defaults template.base.builtins = default_libs
def setup(): # Appengine needs this setup. os.environ["SERVER_SOFTWARE"] = "Dev" os.environ["AUTH_DOMAIN"] = "gmail.com" os.environ["USER_EMAIL"] = "*****@*****.**" datastore_path = rel_path("rietveld_datastore") history_path = rel_path("rietveld_datastore_history") options = {"datastore_path": datastore_path, "history_path": history_path, "clear_datastore": False, "login_url": "/_ah/login", } dev_appserver.SetupStubs("codereview", **options) # Rietveld needs its template libraries loaded like this. library_name = "codereview.library" if not libraries.get(library_name, None): add_to_builtins(library_name)
def show_template(request, template): # Add template tags (so we don't need to load them in each template) add_to_builtins('prototype.template_tags.proto') try: return render(request, template + '.html') except TemplateDoesNotExist: return render(request, "prototype/missing.html", {'current_template': template}) except TemplateSyntaxError as e: params = { 'current_template': template, 'error_type': 'template syntax error', 'error_detail': unicode(e) } except Exception as e: params = { 'current_template': template, 'error_type': 'unexpected error', 'error_detail': unicode(e) } return render(request, "prototype/error.html", params)
def add_to_builtins(module_name): """Add the given module to both Coffin's list of default template libraries as well as Django's. This makes sense, since Coffin libs are compatible with Django libraries. You can still use Django's own ``add_to_builtins`` to register directly with Django and bypass Coffin. Once thing that is special about Coffin is that because {% load %} is not supported in Coffin, *everything* it provides must be registered through the builtins. TODO: Allow passing path to (or reference of) extensions and filters directly. This would make it easier to use this function with 3rd party Jinja extensions that do not know about Coffin and thus will not provide a Library object. XXX/TODO: Why do we need our own custom list of builtins? Our Library object is compatible, remember!? We can just add them directly to Django's own list of builtins. """ builtins.append(import_library(module_name)) django_template.add_to_builtins(module_name)
def load_templatetags(): """ Load custom template tags so they are always available. See https://djangosnippets.org/snippets/342/. In your settings file: TEMPLATE_TAGS = ( "djutils.templatetags.sqldebug", ) Make sure load_templatetags() gets called somewhere, for example in your apps init.py """ # # Note: For reasons I don't understand this code gets ececuted twice when # Django starts. Nothing bad seems to happen so I'll use the technique. # print '=== in utilities init ===' # # Register the template tag as <application>.templatetags.<template tag lib> # try: for lib in settings.TEMPLATE_TAGS: add_to_builtins(lib) except AttributeError: pass
class Library(dict): """ A simple dictionary with register and unregister functions """ def __init__(self): super(Library, self).__init__([(tag, {}) for tag in settings.TAG_TYPES]) self.update([ i for i in settings.LIBRARY.items() if i[0] in settings.TAG_TYPES ]) # Comb through installed apps w/ templatetags looking for native tags for app in djsettings.INSTALLED_APPS: if app == 'native_tags': continue try: mod = import_module('.templatetags', app) except ImportError, e: #print 'Warning: Failed to load module "%s.templatetags": %s' % (app, e) continue # TODO: Make this hurt less for f in listdir(mod.__path__[0]): if f.endswith('.py') and not f.startswith('__'): n = f.split('.py')[0] e = self.load_module('%s.templatetags.%s' % (app, n)) if e is not None: # and settings.DEBUG: print 'Warning: Failed to load module "%s.templatetags.%s": %s' % ( app, n, e) # Load up the native contrib tags for tag_module in settings.TAGS: e = self.load_module(tag_module) if e is not None: # and djsettings.DEBUG: print 'Warning: Failed to load module "%s": %s' % (tag_module, e) # Add the BUILTIN_TAGS to Django's builtins for mod in settings.BUILTIN_TAGS: # if it tries to add iself in here it blows up really badly # this part is done in models.py if mod != 'native_tags.templatetags.native': add_to_builtins(mod)
def wrapped(*args, **kwargs): # Clean out default libraries # Note: template.builtins is merely a convenience import, we have to work # with template.base.builtins for this to work right. template.base.builtins, default_libs = [], template.base.builtins try: # Construct new builtin with only whitelisted tags/filters whitelist = template.Library() for lib in default_libs: for tag in lib.tags: if tag in tags: whitelist.tags[tag] = lib.tags[tag] for filter in lib.filters: if filter in filters: whitelist.filters[filter] = lib.filters[filter] # Install whitelist library and extras as builtins template.base.builtins.append(whitelist) [template.add_to_builtins(e) for e in extra] return func(*args, **kwargs) finally: # Restore the builtins to their former defaults template.base.builtins = default_libs
def build_siteinfo(self, deploy_path=None): tmp_folder = Folder(settings.TMP_DIR) deploy_folder = Folder( (deploy_path, settings.DEPLOY_DIR) [not deploy_path]) if deploy_folder.exists and settings.BACKUP: backup_folder = Folder(settings.BACKUPS_DIR).make() deploy_folder.backup(backup_folder) tmp_folder.delete() tmp_folder.make() settings.DEPLOY_DIR = deploy_folder.path if not deploy_folder.exists: deploy_folder.make() add_to_builtins('hydeengine.templatetags.hydetags') add_to_builtins('hydeengine.templatetags.aym') add_to_builtins('hydeengine.templatetags.typogrify') self.create_siteinfo()
from django import template template.add_to_builtins('common.templatetags.csrfjs')
import re from django.conf.urls import url, patterns, include from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView from django.template import add_to_builtins add_to_builtins('avocado.templatetags.avocado_tags') admin.autodiscover() urlpatterns = patterns( '', url(r'^$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^workspace/', TemplateView.as_view(template_name='index.html'), name='workspace'), url(r'^query/', TemplateView.as_view(template_name='index.html'), name='query'), url(r'^results/', TemplateView.as_view(template_name='index.html'), name='results'), # Serrano-compatible Endpoint url(r'^api/', include('serrano.urls')), url(r'^patient/(?P<mrn>MRN\d+)/$', 'openmrs.views.patient_view', name='patient-detail'),
import unittest from datetime import timedelta, date from django.template import Template, Context, add_to_builtins from django.utils.dateformat import DateFormat from django.utils.translation import ugettext as _ from django.utils.html import escape add_to_builtins('django.contrib.humanize.templatetags.humanize') class HumanizeTests(unittest.TestCase): def humanize_tester(self, test_list, result_list, method): # Using max below ensures we go through both lists # However, if the lists are not equal length, this raises an exception for index in xrange(max(len(test_list), len(result_list))): test_content = test_list[index] t = Template('{{ test_content|%s }}' % method) rendered = t.render(Context(locals())).strip() self.assertEqual(rendered, escape(result_list[index]), msg="%s test failed, produced %s, should've produced %s" % (method, rendered, result_list[index])) def test_ordinal(self): test_list = ('1','2','3','4','11','12', '13','101','102','103','111', 'something else') result_list = ('1st', '2nd', '3rd', '4th', '11th', '12th', '13th', '101st', '102nd', '103rd', '111th', 'something else') self.humanize_tester(test_list, result_list, 'ordinal')
'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher', ) AUTH_USER_MODEL = 'auth.User' import django if django.VERSION < (1, 3): INSTALLED_APPS += ('staticfiles',) # django Pjaxr from django.template import add_to_builtins add_to_builtins('django_pjaxr.templatetags.pjaxr_extends',) TEMPLATE_CONTEXT_PROCESSORS = ('django_pjaxr.context_processors.pjaxr_information',) INSTALLED_APPS += ('django_pjaxr', ) DEFAULT_PJAXR_TEMPLATE = "django_pjaxr/pjaxr.html" ########NEW FILE######## __FILENAME__ = test_views from django.views.generic import TemplateView from django_pjaxr.mixins import IekadouPjaxrMixin class Page1View(IekadouPjaxrMixin, TemplateView):
from django.conf.urls.defaults import * from django.contrib import admin from django import template template.add_to_builtins('django.templatetags.i18n') admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), ) try: from localsettings import * from django.conf import settings urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) except ImportError: pass
from django import template register = template.Library() @register.filter def formatsql(sql, br='break'): sql = sql.replace(',', ', ') if br == 'break': sql = sql.replace('SELECT ', '\t\tSELECT\n\t') sql = sql.replace(' FROM ', '\n\t\tFROM\n\t') sql = sql.replace(' WHERE ', '\n\t\tWHERE\n\t') sql = sql.replace(' INNER JOIN ', '\n\t\tINNER JOIN\n\t') sql = sql.replace(' LEFT OUTER JOIN ', '\n\t\tLEFT OUTER JOIN\n\t') sql = sql.replace(' ORDER BY ', '\n\t\tORDER BY\n\t') # Use Pygments to highlight SQL if it's available try: from pygments import highlight from pygments.lexers import SqlLexer from pygments.formatters import HtmlFormatter sql = highlight(sql, SqlLexer(), HtmlFormatter()) sql = sql.replace('<pre>', '<pre class="sql-query">') except ImportError: import re sql = '<pre class="sql-query">' + re.sub(r'(UNION|ANALYZE|MATCH|AGAINST|ALL|ASC|AS|ALTER|AND|ADD|AUTO_INCREMENT|BETWEEN|BINARY|BOTH|BY|BOOLEAN|CHANGE|CHECK|COLUMNS|COLUMN|CROSS|CREATE|DATABASES|DATABASE|DATA|DELAYED|DESCRIBE|DESC|DISTINCT|DELETE|DROP|DEFAULT|ENCLOSED|ESCAPED|EXISTS|EXPLAIN|FIELDS|FIELD|FLUSH|FOR|FOREIGN|FUNCTION|FROM|GROUP|GRANT|HAVING|IGNORE|INDEX|INFILE|INSERT|INNER JOIN|INTO|IDENTIFIED|IN|IS|IF|JOIN|KEYS|KILL|KEY|LEADING|LIKE|LIMIT|LINES|LOAD|LOCAL|LOCK|LOW_PRIORITY|LEFT|LANGUAGE|MODIFY|NATURAL|NOT|NULL|NEXTVAL|OPTIMIZE|OPTION|OPTIONALLY|ORDER BY|OUTFILE|OR|OUTER|ON|PROCEEDURE|PROCEDURAL|PRIMARY|READ|REFERENCES|REGEXP|RENAME|REPLACE|RETURN|REVOKE|RLIKE|RIGHT|SHOW|SONAME|STATUS|STRAIGHT_JOIN|SELECT|SETVAL|SET|TABLES|TEMINATED|TO|TRAILING|TRUNCATE|TABLE|TEMPORARY|TRIGGER|TRUSTED|UNIQUE|UNLOCK|USE|USING|UPDATE|VALUES|VARIABLES|VIEW|WITH|WRITE|WHERE|ZEROFILL|TYPE|XOR)', r'<span class="hilight">\1</span>', sql) + '</pre>' pass sql = sql.replace('\t\t', '<span class="indent">') sql = sql.replace('\n\t', '</span>\n') return mark_safe(sql) template.add_to_builtins('debug_toolbar.panels.sql')
from django.template import add_to_builtins add_to_builtins('snippify.globaltags.gravatar') add_to_builtins('snippify.globaltags.snippify')
import re from django.conf.urls import url, patterns, include from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView from django.template import add_to_builtins add_to_builtins('avocado.templatetags.avocado_tags') admin.autodiscover() urlpatterns = patterns('', # Landing Page url(r'^$', 'harvest_project.views.landing', name='landing'), # Cilantro Pages url(r'^workspace/', TemplateView.as_view(template_name='index.html'), name='workspace'), url(r'^query/', TemplateView.as_view(template_name='index.html'), name='query'), url(r'^results/', TemplateView.as_view(template_name='index.html'), name='results'), # Serrano-compatible Endpoint url(r'^api/', include('serrano.urls')), # Administrative components url(r'^admin/', include(admin.site.urls)), ) # In production, these two locations must be served up statically urlpatterns += patterns('django.views.static', url(r'^{0}(?P<path>.*)$'.format(re.escape(settings.MEDIA_URL.lstrip('/'))), 'serve', { 'document_root': settings.MEDIA_ROOT
import django from django.conf import settings from .cache import patch_cache_key_funcs if django.VERSION[:2] < (1, 7): from django.template import add_to_builtins # moved in Django 1.8 if getattr(settings, 'HOST_OVERRIDE_URL_TAG', False): # pragma: no cover add_to_builtins('django_hosts.templatetags.hosts_override') patch_cache_key_funcs()
from django import template # This will add the localsite tags as built-in tags, and override the existing # {% url %} tag in Django. template.add_to_builtins(__name__ + '.localsite')
# -*- mode: python; coding: utf-8; -*- from django import template from django.contrib.contenttypes.models import ContentTypeManager from django.conf import settings from lib.db import ctm_get from lib.template_loaders import cached_get_template from lib import appcheck template.add_to_builtins("lib.templatetags.links") template.add_to_builtins("lib.templatetags.messages") template.add_to_builtins("blog.templatetags.datelinks") template.add_to_builtins("typogrify.templatetags.typogrify") template.add_to_builtins("lib.templatetags.ifapp") template.add_to_builtins("revcanonical.templatetags.revcanontags") #if getattr(settings, 'ORM_DEBUG'): #template.add_to_builtins("debug.templatetags.orm_debug") ContentTypeManager.get = ctm_get from django.forms.util import ErrorDict if 'as_json' not in ErrorDict.__dict__: from lib.ajax import as_json ErrorDict.as_json = as_json if appcheck.watchlist: import watchlist.mail #template.loader.get_template = cached_get_template
from oneflow.base.models import Configuration from ..models import ( # NOQA User, Article, Read, BaseFeed, Subscription, HelpContent, Folder, # Imported for `edit_field` Processor, ChainedItem, WebSite, HistoricalArticle, IMPORT_STATUS, CONTENT_TYPES_FINAL, ) from ..gr_import import GoogleReaderImport LOGGER = logging.getLogger(__name__) # Avoid repetitive {% load … %} in templates. add_to_builtins('django.templatetags.i18n') add_to_builtins('django.templatetags.cache') add_to_builtins('djangojs.templatetags.js') add_to_builtins('pipeline.templatetags.compressed') add_to_builtins('absolute.templatetags.absolute_future') add_to_builtins('markdown_deux.templatetags.markdown_deux_tags') add_to_builtins('widget_tweaks.templatetags.widget_tweaks') add_to_builtins('endless_pagination.templatetags.endless') add_to_builtins('sparks.django.templatetags.all') add_to_builtins('oneflow.core.templatetags.coretags') add_to_builtins('inplaceeditform.templatetags.inplace_edit') # if settings.TEMPLATE_DEBUG: # add_to_builtins('template_debug.templatetags.debug_tags') # ———————————————————————————————————————————————————————————————————— Wrappers
# Quick tests for the markup templatetags (django.contrib.markup) import re import unittest from django.template import Template, Context, add_to_builtins from django.utils.html import escape add_to_builtins('django.contrib.markup.templatetags.markup') class Templates(unittest.TestCase): def test_textile(self): try: import textile except ImportError: textile = None textile_content = """Paragraph 1 Paragraph 2 with "quotes" and @code@""" t = Template("{{ textile_content|textile }}") rendered = t.render(Context(locals())).strip() if textile: self.assertEqual( rendered.replace('\t', ''), """<p>Paragraph 1</p> <p>Paragraph 2 with “quotes” and <code>code</code></p>""") else: self.assertEqual(rendered, escape(textile_content))
from django import template # add core templatetags to builtin so that you don't have to invoke {% load core %} in every template template.add_to_builtins('ella.core.templatetags.core') # keep this here for backwards compatibility template.add_to_builtins('ella.core.templatetags.related') # and custom urls template.add_to_builtins('ella.core.templatetags.custom_urls_tags') # and the same for i18n template.add_to_builtins('django.templatetags.i18n') # and photos are always useful template.add_to_builtins('ella.photos.templatetags.photos')
from django import template template.add_to_builtins('mypage.pages.templatetags.xextends')
'with "django.contrib.auth".') if 'permission.backends.PermissionBackend' \ not in settings.AUTHENTICATION_BACKENDS: warnings.warn( Warning, '"permission.backends.PermissionBackend" is not found in ' '`AUTHENTICATION_BACKENDS`.') if 'permission.backends.RoleBackend' \ not in settings.AUTHENTICATION_BACKENDS: warnings.warn( Warning, '"permission.backends.RoleBackend" is not found in ' '`AUTHENTICATION_BACKENDS`.') # Register templatetags in builtin if settings.PERMISSION_BUILTIN_TEMPLATETAGS: from django.template import add_to_builtins add_to_builtins('permission.templatetags.permission_tags') # Extend User class if settings.PERMISSION_EXTEND_USER_CLASS: from django.contrib import auth from django.contrib.auth.models import User from django.contrib.auth.models import AnonymousUser def _user_has_role(user, role): anon = user.is_anonymous() active = user.is_active for backend in auth.get_backends(): if anon or active or backend.supports_inactive_user: if hasattr(backend, 'has_role'): if backend.has_role(user, role): return True
def render_to_string(template_name, dictionary=None, context_instance=None): """ Loads the given template_name and renders it with the given dictionary as context. The template_name may be a string to load a single template using get_template, or it may be a tuple to use select_template to find one of the templates in the list. Returns a string. """ dictionary = dictionary or {} if isinstance(template_name, (list, tuple)): t = select_template(template_name) else: t = get_template(template_name) if context_instance: context_instance.update(dictionary) else: context_instance = Context(dictionary) return t.render(context_instance) def select_template(template_name_list): "Given a list of template names, returns the first that can be loaded." for template_name in template_name_list: try: return get_template(template_name) except TemplateDoesNotExist: continue # If we get here, none of the templates could be loaded raise TemplateDoesNotExist(', '.join(template_name_list)) add_to_builtins('django.template.loader_tags')
# browser, we need to tell proxies to serve different versions. from django.utils.cache import patch_vary_headers patch_vary_headers(response, ['User-Agent']) return HttpResponse(render_to_string(request, template_name, data), content_type='%s; charset=%s' % (mimetype, settings.DEFAULT_CHARSET)) def JSONResponse(pyobj): from ragendja.json import JSONResponse as real_class global JSONResponse JSONResponse = real_class return JSONResponse(pyobj) def TextResponse(string=''): return HttpResponse(string, content_type='text/plain; charset=%s' % settings.DEFAULT_CHARSET) # Load app modules after all definitions, so imports won't break. # Register global template libraries. for lib in getattr(settings, 'GLOBALTAGS', ()): add_to_builtins(lib) # This is needed by app_prefixed_loader. app_template_dirs = get_app_dirs('templates')
import re from django.conf.urls.defaults import url, patterns from django.conf import settings from django.template import add_to_builtins add_to_builtins('core.templatetags.core_tags') urlpatterns = patterns('', # Poor man's flatpages.. url(r'^$', 'core.views.direct_to_template', {'path': 'index'}, name='index'), url(r'^(?P<path>.*)/$', 'core.views.direct_to_template', name='page'), ) # In production, these two locations must be served up statically urlpatterns += patterns('django.views.static', url(r'^%s(?P<path>.*)$' % re.escape(settings.MEDIA_URL.lstrip('/')), 'serve', { 'document_root': settings.MEDIA_ROOT }), url(r'^%s(?P<path>.*)$' % re.escape(settings.STATIC_URL.lstrip('/')), 'serve', { 'document_root': settings.STATIC_ROOT }), )
from django import template project_tags = [ 'www.apps.social.templatetags.social', ] for t in project_tags: template.add_to_builtins(t)
""" # Python imports import constants import logging import os import webapp2 from webapp2_extras import sessions from django import template from django.template import Context, Template from django.template.loader import get_template import handlers from utils import time_util urls = [ ('/', handlers.MainHandler), ('/_ah/warmup', handlers.Warmup), ('/snake', handlers.SnakeHandler), ('/signup', handlers.SignupHandler), ('/login', handlers.LoginHandler), ('/user', handlers.UserHandler), ] template.add_to_builtins('django.contrib.humanize.templatetags.humanize') template.add_to_builtins('filters.filters') app = webapp2.WSGIApplication(urls, config=constants.APP_CONFIG)
from __future__ import unicode_literals from django import template # This will add the localsite tags as built-in tags, and override the existing # {% url %} tag in Django. template.add_to_builtins(__name__ + '.localsite')
site.register(Notification, NotificationAdmin) site.register(Complexity, ComplexityAdmin) site.register(Contingency, ContingencyAdmin) site.register(ContingencyAction, ContingencyActionAdmin) site.register(ContingencyNotification, ContingencyNotificationAdmin) site.register(Profile, ModelAdmin) site.register(Action, ActionAdmin) site.register(AreaAchievement, AreaAchievementAdmin) site.register(RoadSegment, RoadSegmentAdmin) site.register(TrailSegment, TrailSegmentAdmin) site.register(SignInspection, SignInspectionAdmin) site.register(BurningPrescription, BurningPrescriptionAdmin) site.register(EdgingPlan, EdgingPlanAdmin) site.register(LightingSequence, LightingSequenceAdmin) site.register(BriefingChecklist, BriefingChecklistAdmin) site.register(ExclusionArea, ExclusionAreaAdmin) site.register(Document, DocumentAdmin) site.register(TrafficControlDiagram, ModelAdmin) site.register(ProposedAction, ProposedActionAdmin) site.register(Evaluation, EvaluationAdmin) site.register(PostBurnChecklist, PostBurnChecklistAdmin) site.register(OperationalOverview, OperationalOverviewAdmin) site.register(BurnState, BurnStateAdmin) site.register(PrescribedBurn, PrescribedBurnAdmin) site.register(AircraftBurn, AircraftBurnAdmin) # add our own texify filter to the builtins here. add_to_builtins('pbs.prescription.templatetags.texify')
from django.template import add_to_builtins add_to_builtins('account.templatetags.account_tags')
# performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } from django.template import add_to_builtins add_to_builtins('django.templatetags.i18n') add_to_builtins('sekizai.templatetags.sekizai_tags')
import base from django.template import add_to_builtins add_to_builtins('mysite.att.templatetags.att_tags') import datetime def auto_fill_trans(dept=None, st=datetime.datetime.now()): from mysite.personnel.models import Employee from models import CheckExact import random now = st st = datetime.date(now.year, now.month, 1) et = datetime.date(now.year, now.month + 1, 1) cday = st if dept: emps = Employee.objects.filter(DeptID__code__exact=dept) else: emps = Employee.objects.all() while cday < et: #print "current date :%s"%cday for u in emps: #print "%s current user :%s"%(cday,u) for i in range(2): insert = True am = datetime.datetime(cday.year, cday.month, cday.day, 07, 45, int(random.random() * 100) % 60) pm = datetime.datetime(cday.year, cday.month, cday.day, 18, 0, int(random.random() * 100) % 60) if cday.weekday in [5, 6]:
# Set default settings set_default( 'OBJECT_PERMISSION_DEFAULT_HANDLER_CLASS', 'object_permission.handlers.base.ObjectPermHandler') set_default('OBJECT_PERMISSION_EXTRA_DEFAULT_PERMISSIONS', ['view']) set_default('OBJECT_PERMISSION_BUILTIN_TEMPLATETAGS', True) set_default('OBJECT_PERMISSION_AUTODISCOVER', True) set_default('OBJECT_PERMISSION_HANDLER_MODULE_NAME', 'ophandler') # Load site (this must be after the default settings has complete) from sites import site # Regist templatetags for ObjectPermission if settings.OBJECT_PERMISSION_BUILTIN_TEMPLATETAGS: from django.template import add_to_builtins add_to_builtins('%s.templatetags.object_permission_tags' % app_label) # Add extra default permission def _get_all_permissions(opts): "Returns (codename, name) for all permissions in the given opts." perms = [] for action in settings.OBJECT_PERMISSION_EXTRA_DEFAULT_PERMISSIONS: perms.append((_get_permission_codename(action, opts), u'Can %s %s' % (action, opts.verbose_name_raw))) return perms + list(opts.permissions) def create_permissions(app, created_models, verbosity, **kwargs): from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission app_models = get_models(app) if not app_models: return for klass in app_models:
#from django.contrib.admin import autodiscover from django import template from ella.utils.installedapps import call_modules from ella.newman.sites import site from ella.newman.options import NewmanModelAdmin, NewmanInlineModelAdmin, NewmanStackedInline, NewmanTabularInline from ella.newman.generic import BaseGenericInlineFormSet, GenericInlineModelAdmin, GenericStackedInline, GenericTabularInline def autodiscover(): call_modules(auto_discover=( 'newman_admin', 'admin', )) # add newman templatetags to builtin template.add_to_builtins('ella.newman.templatetags.newman') # newman url for object for other apps, FEs... from ella.newman.utils import get_newman_url
from os import path import datetime from django import template from django.conf import settings from django.test import TestCase import ttag from ttag.tests.setup import as_tags, template_tags template.add_to_builtins(as_tags.__name__) template.add_to_builtins(template_tags.__name__) def render(contents, extra_context=None): return template.Template(contents).render(template.Context(extra_context)) class AsTag(TestCase): def test_simple(self): """ A tag with named arguments works with or without the argument as long as a default value is set. """ self.assertEqual(render('{% fish_as as out %}-{{ out }}'), '-fish') self.assertEqual(render('{% another_fish_as as out %}-{{ out }}'), '-fish') def test_optional(self): """ A tag with named arguments works with or without the argument as long
import logging, logging.config, logging.handlers from django.conf import settings # Configure logging first if not logging.getLogger().handlers: logging.config.fileConfig('./logging.conf') _log = logging.getLogger() _log.setLevel(settings.LOG_DEBUG and logging.DEBUG or logging.INFO) # Add commonly used templatetags to the builtins space so that we don't have # to keep issuing {% load %} calls in every template. from django.template import add_to_builtins add_to_builtins('django.templatetags.cache') add_to_builtins('django.templatetags.i18n') add_to_builtins('common.templatetags.commontags') add_to_builtins('siteconfig.templatetags.siteconfigtags') add_to_builtins('campaign.templatetags.campaigntags') add_to_builtins('event.templatetags.eventtags') add_to_builtins('payment.templatetags.paymenttags') add_to_builtins('photo.templatetags.phototags') add_to_builtins('twitter.templatetags.twittertags') # Invoke customizations to django.contrib apps and third-party apps. import extensions.extend import socket socket.setdefaulttimeout(20)
self.buf.append('{{%s%s}}'%(val,'|force_escape' if code.escape else '')) else: self.buf.append('{%% %s %%}'%code.val) if code.block: self.visit(code.block) if not code.buffer: codeTag = code.val.strip().split(' ',1)[0] if codeTag in self.autocloseCode: self.buf.append('{%% end%s %%}'%codeTag) def attributes(self,attrs): return "{%% __pyjade_attrs %s %%}"%attrs from django import template template.add_to_builtins('pyjade.ext.django.templatetags') from django.utils.translation import trans_real def decorate_templatize(func): def templatize(src, origin=None): html = process(src,compiler=Compiler) return func(html, origin) return templatize trans_real.templatize = decorate_templatize(trans_real.templatize) from loader import Loader
from django.dispatch import receiver from django.utils.importlib import import_module from django.utils.six import add_metaclass logger = logging.getLogger(__name__) # set the default place to send logs LOGSTASH_ADDRESS = getattr(settings, "LOGSTASH_ADDRESS", 'logs.rc.pdx.edu:8000') # set the default probability of when to clear sessions CLEAR_SESSIONS_PROBABILITY = getattr(settings, "CLEAR_SESSIONS_PROBABILITY", 0.01) forms.Form.required_css_class = "required" forms.ModelForm.required_css_class = "required" Field.required_css_class = "required" add_to_builtins('django.contrib.staticfiles.templatetags.staticfiles') # add the arc template tags to the builtin tags, and the bootstrap tag add_to_builtins('arcutils.templatetags.arc') add_to_builtins('arcutils.templatetags.bootstrap') # add some helpful methods to the formset class FormSetMixin(object): def iter_with_empty_form_first(self): """ Iterates over the forms in this formset, but the first form yielded is the empty one. This simplifies the logic in templates, since the empty_form is no longer a special case """ yield self.empty_form for form in iter(self):
from django.template import add_to_builtins add_to_builtins('nbio.django.templatetags')
from django.db import models, connection from django.db.models import Q from django.template import add_to_builtins add_to_builtins('mysite.iclock.templatetags.iclock_tags') def getDefaultJsonDataTemplate(model, options={}): additionFields = [] exceptionFields = [] additionHeader = {} try: exceptionFields = options.getlist('exception_fields') except: pass else: try: additionFields = options.getlist('addition_fields') except: pass else: if additionFields: fs = [] for f in additionFields: header = '' field = f filter = '' if f.find('</th>') >= 0: header, field = f.split('</th>', 1) header += '</th>' additionHeader[field] = header
# Quick tests for the markup templatetags (django.contrib.markup) import re import unittest from django.template import Template, Context, add_to_builtins from django.utils.html import escape add_to_builtins("django.contrib.markup.templatetags.markup") class Templates(unittest.TestCase): def test_textile(self): try: import textile except ImportError: textile = None textile_content = """Paragraph 1 Paragraph 2 with "quotes" and @code@""" t = Template("{{ textile_content|textile }}") rendered = t.render(Context(locals())).strip() if textile: self.assertEqual( rendered.replace("\t", ""), """<p>Paragraph 1</p> <p>Paragraph 2 with “quotes” and <code>code</code></p>""", )
def process_request(self, request): # This adds all tags registered separately through native_tags to the builtins add_to_builtins('native_tags.templatetags.native')