def test_sitecats_url(self): tpl = '{% load sitecats %}{% sitecats_url %}' self.assertRaises(TemplateSyntaxError, render_string, tpl) # testing UNRESOLVED_URL_MARKER context = Context({'my_category': self.cat1, 'my_list': self.cl_cat1}) tpl = '{% load sitecats %}{% sitecats_url for my_category using my_list %}' result = render_string(tpl, context) self.assertEqual(result, UNRESOLVED_URL_MARKER) # testing ModelWithCategory.get_category_absolute_url() self.cl_cat1.set_obj(self.art1) expected_url = '%s/%s' % (self.cat1.id, self.art1.title) tpl = '{% load sitecats %}{% sitecats_url for my_category using my_list %}' result = render_string(tpl, context) self.assertEqual(result, expected_url) tpl = '{% load sitecats %}{% sitecats_url for my_category using my_list as someurl %}' render_string(tpl, context) self.assertEqual(context.get('someurl'), expected_url) # testing CategoryList.show_links tpl = '{% load sitecats %}{% sitecats_url for my_category using my_list %}' result = render_string(tpl, Context({'my_category': self.cat2, 'my_list': self.cl_cat2})) self.assertEqual(result, str(self.cat2.id))
def render(self, context, instance, placeholder): template_vars = { 'placeholder': placeholder, } template_vars['object'] = instance # locate the plugins assigned to the given page for the indicated placeholder lang = None if context.has_key('request'): lang = context['request'].LANGUAGE_CODE else: lang = settings.LANGUAGE_CODE #print 'language CONTEXT FOR PLUGIN:', lang plugins = CMSPlugin.objects.filter(page=instance.parent_page, placeholder=placeholder, language=lang) plugin_output = [] template_vars['parent_plugins'] = plugins for plg in plugins: #print 'added a parent plugin:', plg, plg.__class__ # use a temporary context to prevent plugins from overwriting context tmpctx = Context() tmpctx.update(template_vars) inst, name = plg.get_plugin_instance() #print 'got a plugin instance:', inst outstr = inst.render_plugin(tmpctx, placeholder) plugin_output.append(outstr) #print 'render result:', outstr template_vars['parent_output'] = plugin_output context.update(template_vars) return context
def submit_row(context): """ Display the row of buttons for delete and save. """ add = context['add'] change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] show_save = context.get('show_save', True) show_save_and_continue = context.get('show_save_and_continue', True) has_add_permission = context['has_add_permission'] has_change_permission = context['has_change_permission'] has_view_permission = context['has_view_permission'] has_editable_inline_admin_formsets = context['has_editable_inline_admin_formsets'] can_save = (has_change_permission and change) or (has_add_permission and add) or has_editable_inline_admin_formsets can_save_and_continue = not is_popup and can_save and has_view_permission and show_save_and_continue can_change = has_change_permission or has_editable_inline_admin_formsets ctx = Context(context) ctx.update({ 'can_change': can_change, 'show_delete_link': ( not is_popup and context['has_delete_permission'] and change and context.get('show_delete', True) ), 'show_save_as_new': not is_popup and has_change_permission and change and save_as, 'show_save_and_add_another': ( has_add_permission and not is_popup and (not save_as or add) and can_save ), 'show_save_and_continue': can_save_and_continue, 'show_save': show_save and can_save, 'show_close': not(show_save and can_save) }) return ctx
def sphblog_showblogpost(context, post): ret = {'post': post, 'blogpost': post.blogpostextension_set.get(), } retctx = Context(context) retctx.update(ret) return retctx
def render(self, loader): """ Function - create html structure of folder's tree Parameters ========== loader - django.template.loader object """ if loader is django.template.loader: ctx = Context() t = loader.get_template('tinymce_images_foldertree.html') if self.is_top(): ctx['is_top'] = 1 else: ctx['relpath'] = self.path() ctx['path'] = self._path ctx['files_count'] = self.get_files_count() ctx['folders_count'] = self.get_folders_count() # for each item calls render function for item in self._items: ctx['inner'] = ctx.get('inner', '') + item.render(loader) return t.render(ctx)
def render_globals(self): print "!!" result = "" if self.template_globals: self.templates_list.insert(0, self.template_globals) default_dict = {"component": self, "window": self} context = Context(default_dict) for file_name in self.templates_list: if isinstance(file_name, (tuple, list)): file_context = Context(default_dict) file_context.update(file_name[1]) file_name = file_name[0] else: file_context = context template = get_template(file_name) try: text = template.render(file_context) except Exception as err: # не надо молчать если есть проблемы raise ApplicationLogicException( "Render error for template {} {}".format(file_name, get_exception_description(err)) ) # Комментарий для отладки remark = "\n//========== TEMPLATE: %s ==========\n" % file_name result += remark + text # Отмечает строку как безопасную (фильтр safe) для шаблонизатора return mark_safe(result)
def show_post(context, post): ''' shows an actual blog post ''' ctx = {'post': post, 'published_comment_count': post.published_comment_count()} ret = Context(context) ret.update(ctx) return ret
def get_context(context_dict=None, current_app='', request_path=None, user_data=None): user = user_data if hasattr(user_data, '_meta') else MockUser(user_data) context_dict = context_dict or {} context_updater = { 'request': MockRequest(request_path, user), } if user_data: context_updater['user'] = user context_dict.update(context_updater) context = Context(context_dict) context.template = mock.MagicMock() context.template.engine.string_if_invalid = '' if VERSION >= (1, 10): match = mock.MagicMock() match.app_name = current_app context.resolver_match = match else: context._current_app = current_app return context
def render_cell(self, state, obj, render_context): """Renders the table cell containing column data.""" datagrid = state.datagrid rendered_data = self.render_data(state, obj) url = '' css_class = '' if self.link: try: url = self.link_func(state, obj, rendered_data) except AttributeError: pass if self.css_class: if six.callable(self.css_class): css_class = self.css_class(obj) else: css_class = self.css_class key = "%s:%s:%s:%s" % (state.last, rendered_data, url, css_class) if key not in state.cell_render_cache: ctx = Context(render_context) ctx.update({ 'column': self, 'column_state': state, 'css_class': css_class, 'url': url, 'data': mark_safe(rendered_data) }) state.cell_render_cache[key] = \ mark_safe(datagrid.cell_template_obj.render(ctx)) return state.cell_render_cache[key]
def submit_row(context): """ 移除"保存后添加"按钮 移除"保存继续编辑"按钮 添加"保存为草稿"按钮 """ # ctx = original_submit_row(context) change = context['change'] is_popup = context['is_popup'] save_as = context['save_as'] show_save = context.get('show_save', True) show_save_and_continue = context.get('show_save_and_continue', True) from django.template.context import Context ctx = Context(context) ctx.update({ 'show_delete_link': True, 'show_save_as_new': not is_popup and change and save_as, 'show_save_and_add_another': ( context['has_add_permission'] and not is_popup and (not save_as or context['add']) ), 'show_save_and_continue': not is_popup and context['has_change_permission'] and show_save_and_continue, 'show_save': False, 'show_save_as_draft': True, }) # ctx.update({ # 'show_save_and_add_another': False, # 'show_save_as_draft': True, # 'show_save_and_continue': False, # }) print(ctx) return ctx
def __init__(self, dict, instance, placeholder, processors=None, current_app=None): Context.__init__(self, dict, current_app=current_app) if processors is None: processors = () else: processors = tuple(processors) for processor in DEFAULT_PLUGIN_CONTEXT_PROCESSORS + get_standard_processors('CMS_PLUGIN_CONTEXT_PROCESSORS') + processors: self.update(processor(instance, placeholder))
def render(self, context): form = FriendsSearchForm() ctx = Context() [ ctx.update(d) for d in context.dicts ] ctx.update({ 'friends_search_form' : form, }) return render_to_string('friends/tags/search_form{0}.html'.format(self.postfix), ctx)
def sphboard_displayCategories(context, categories, maxDepth=5, level=-1): if maxDepth < level: return { } ret = {'categories': [c for c in categories if c.get_category_type().is_displayed()], 'level': level + 1, 'maxDepth': maxDepth} retctx = Context(context) retctx.update(ret) return retctx
def render(self, **kwargs): assert 'request' in kwargs template = getattr(self, 'render_template', getattr(self.get_content(), 'render_template', None) if hasattr(self, 'get_content') else None) if not template: raise NotImplementedError('No template defined for rendering %s content.' % self.__class__.__name__) context = Context({'content': self}) if 'context' in kwargs: context.update(kwargs['context']) return render_to_string(template, context, context_instance=RequestContext(kwargs['request']))
def __init__(self, dict=None, processors=None, current_app=None): Context.__init__(self, dict, current_app=current_app) if processors is None: processors = () else: processors = tuple(processors) for processor in ( tuple(p for p in get_standard_processors() if getattr(p, "requires_request", True) == False) + processors ): self.update(processor())
def __unicode__(self): if self.template_path: t = template.loader.get_template(self.template_path) ctxt = Context() ctxt['_tab'] = self ctxt['_widgets'] = self.widgets ctxt.update(self.widgets) return t.render(ctxt) else: return '\n'.join([w.__unicode__() for w in self.widgets.values()])
def sphboard_displayCategories(context, categories, maxDepth=5, level=-1): if maxDepth < level: return {} ret = { "categories": [c for c in categories if c.get_category_type().is_displayed()], "level": level + 1, "maxDepth": maxDepth, } retctx = Context(context) retctx.update(ret) return retctx
def __init__(self, request, dict=None, current_app=None): # If there is any reason to site-global context processors for plugins, # I'd like to know the usecase, and it could be implemented here. if current_app is None: # Avoid RemovedInDjango110Warning Context.__init__(self, dict) else: Context.__init__(self, dict, current_app=current_app) for processor in _STANDARD_REQUEST_CONTEXT_PROCESSORS: self.update(processor(request))
def get_mock_context(app=None, path=None, user_authorized=False, tree_item=None, put_var=None): ctx = Context( { 'request': MockRequest(path, user_authorized), 't2_root2_title': 'my_real_title', 'art_id': 10, 'tree_item': tree_item, 'somevar_str': 'articles_list', 'somevar_list': ['a', 'b'], 'put_var': put_var }, current_app=app ) ctx.template = mock.MagicMock() ctx.template.engine.string_if_invalid = '' return ctx
def render(self, **kwargs): assert 'request' in kwargs template = self.render_template or self._find_render_template_path(self.region) if not template: raise NotImplementedError('No template found for rendering %s content. I tried ["%s"].' % (self.__class__.__name__, '", "'.join(self._render_template_paths(self.region)))) context = Context() if 'context' in kwargs: context.update(kwargs['context']) context['content'] = self if hasattr(self, 'extra_context') and callable(self.extra_context): context.update(self.extra_context(kwargs['request'])) return render_to_string(template, context, context_instance=RequestContext(kwargs['request']))
def render(template_name, dictionary=None, context=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name) else: template = get_template(template_name) dictionary = dictionary or {} if context is None: context = Context(dictionary) else: context.update(dictionary) data = {} [data.update(d) for d in context] return template.render(**data)
def render(self, context=None, request=None): # TODO: require context to be a dict -- through a deprecation path? if not isinstance(context, Context): if request is None: context = Context(context) else: # The following pattern is required to ensure values from # context override those from template context processors. original_context = context context = RequestContext(request) if original_context: context.push(original_context) return self.template.render(context)
def render_listview(self, render_context=None): """ Renders the standard list view of the grid. This can be called from templates. """ try: if render_context is None: render_context = self._build_render_context() self.load_state(render_context) if self.page.has_next(): next_page_number = self.page.next_page_number() else: next_page_number = None if self.page.has_previous(): previous_page_number = self.page.previous_page_number() else: previous_page_number = None context = Context({ 'datagrid': self, 'is_paginated': self.page.has_other_pages(), 'results_per_page': self.paginate_by, 'has_next': self.page.has_next(), 'has_previous': self.page.has_previous(), 'page': self.page.number, 'next': next_page_number, 'previous': previous_page_number, 'last_on_page': self.page.end_index(), 'first_on_page': self.page.start_index(), 'pages': self.paginator.num_pages, 'hits': self.paginator.count, 'page_range': self.paginator.page_range, }) context.update(self.extra_context) context.update(render_context) return mark_safe(render_to_string(self.listview_template, context)) except Exception: trace = traceback.format_exc(); logging.error('Failed to render datagrid:\n%s' % trace, extra={ 'request': self.request, }) return mark_safe('<pre>%s</pre>' % trace)
def healed_context(context): """ .. testcase:: HealedContextTestCase """ if not isinstance(context, BaseContext): context = Context(context) original_context_length = len(context.dicts) yield context ctx_length = len(context.dicts) while ctx_length > 1 and ctx_length > original_context_length: logger.debug('Removing excess context dicts (target size {0},' 'working size {1})'.format(original_context_length, ctx_length)) context.pop() ctx_length = len(context.dicts)
def render_to_response(template_name, dictionary=None, context_instance=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name) else: template = get_template(template_name) dictionary = dictionary or {} if context_instance is None: context_instance = Context(dictionary) else: context_instance.update(dictionary) data = {} [data.update(d) for d in context_instance] return HttpResponse(template.render(**data))
def ajax_task_edit(request, pk): """ Ajax call to edit a task. @param pk: the task's pk @return (in JSON format): {error: error message} if there's been an error {html: form html} if GET request or there are errors in the form {success: true} if the form was successfully submitted """ return_data = None try: # get task to edit task_to_edit = Task.objects.get(pk=pk) # check if user allowed to edit task if task_to_edit.user != request.user.get_profile(): raise Exception('You are not allowed to edit task %s.' % pk) # get form data form_data = None if request.method == 'POST': form_data = request.POST # create task form task_form = TaskForm(UserProfile=request.user.get_profile(), instance=task_to_edit, data=form_data) # check what to return if request.method == 'POST' and task_form.is_valid(): task_form.save() return_data = simplejson.dumps({'success': True,}) else: # create template context template_context = Context({ 'form': task_form, 'submit_value': 'Save changes', }) # add CSRF token to prevent errors from not using RequestContext template_context.update(csrf(request)) # get the form's html form_html = get_template('sussedical/_form.djhtml').render(template_context) return_data = simplejson.dumps({'html': form_html,}) except Exception as e: return_data = simplejson.dumps({'error': e.message,}) return HttpResponse(return_data, mimetype='application/javascript')
def render_to_response(template_name, dictionary=None, context_instance=None): if isinstance(template_name, (list, tuple)): template = select_template(template_name) else: template = get_template(template_name) dictionary = dictionary or {} if context_instance is None: context_instance = Context(dictionary) else: context_instance.update(dictionary) data = {} [data.update(d) for d in context_instance] data = uni_str(data, encoding=settings.DEFAULT_CHARSET, key_convert=False) return HttpResponse(template.render(**data))
def get_context_processors_content(request): """ return the context_processors dict context """ context = Context() try: from django.utils.module_loading import import_string from django.template.context import _builtin_context_processors context_processors = _builtin_context_processors context_processors += tuple(settings.TEMPLATE_CONTEXT_PROCESSORS) cp_func_list = tuple(import_string(path) for path in context_processors) for processors in cp_func_list: context.update(processors(request)) except Exception as e: context = Context() return context
def render_cell(self, state, obj, render_context): """Renders the table cell containing column data.""" datagrid = state.datagrid try: rendered_data = self.render_data(state, obj) except Exception as e: logging.error('Error when calling render_data for DataGrid Column' ' %r: %s', self, e, exc_info=1) rendered_data = None if render_context: url = render_context.get('_datagrid_object_url') else: url = None css_class = '' if self.link: try: url = self.link_func(state, obj, rendered_data) except AttributeError: pass if self.css_class: if six.callable(self.css_class): css_class = self.css_class(obj) else: css_class = self.css_class key = "%s:%s:%s:%s" % (state.last, rendered_data, url, css_class) if key not in state.cell_render_cache: ctx = Context(render_context) ctx.update({ 'column': self, 'column_state': state, 'css_class': css_class, 'url': url, 'data': mark_safe(rendered_data) }) state.cell_render_cache[key] = \ mark_safe(datagrid.cell_template_obj.render(ctx)) return state.cell_render_cache[key]
def render_cell(self, obj, render_context): """ Renders the table cell containing column data. """ rendered_data = self.render_data(obj) url = '' css_class = '' if self.link: try: url = self.link_func(obj, rendered_data) except AttributeError: pass if self.css_class: if callable(self.css_class): css_class = self.css_class(obj) else: css_class = self.css_class key = "%s:%s:%s:%s" % (self.last, rendered_data, url, css_class) if key not in self.cell_render_cache: if not self.datagrid.cell_template_obj: self.datagrid.cell_template_obj = \ get_template(self.datagrid.cell_template) if not self.datagrid.cell_template_obj: logging.error("Unable to load template '%s' for datagrid " "cell. This may be an installation issue." % self.datagrid.cell_template, extra={ 'request': self.datagrid.request, }) ctx = Context(render_context) ctx.update({ 'column': self, 'css_class': css_class, 'url': url, 'data': mark_safe(rendered_data) }) self.cell_render_cache[key] = \ mark_safe(self.datagrid.cell_template_obj.render(ctx)) return self.cell_render_cache[key]
def handle_noargs(self, **options): import datetime from django.core.mail import send_mail from Users.userfunctions import ScheduleMessages from django.template.loader import get_template from django.template.context import Context from django.core.mail.message import EmailMessage t = get_template('emailTemplate.html') today = datetime.datetime.today() tomorrow = today + datetime.timedelta(1) day_after = tomorrow + datetime.timedelta(1) today_messages = ScheduleMessages(today.month,today.year).get_message_for_day(today.day) tomorrow_messages = ScheduleMessages(tomorrow.month,tomorrow.year).get_message_for_day(tomorrow.day) day_after_messages = ScheduleMessages(day_after.month,day_after.year).get_message_for_day(day_after.day) #stri = "Tasks:- \n Today's:" + "\n" + today_messages + "\n" + "Tomorrow:" + "\n" + tomorrow_messages + " Day After: " + "\n" + day_after_messages c = Context({'today':today , 'tomorrow':tomorrow , 'day_after':day_after}) msg = EmailMessage(subject = "Daily Notifications" , body = t.render(c), from_email ='*****@*****.**', to = ['*****@*****.**']) msg.content_subtype = "html" # Main content is now text/html msg.send() exit()
def render_mako_tostring(template_name, dictionary={}, context_instance=None): ''' render_mako_tostring without RequestContext @note: 因为返回是string,所以这个方法适合include的子页面用 ''' mako_temp = mylookup.get_template(template_name) if context_instance: # RequestContext(request) context_instance.update(dictionary) else: # 默认为Context context_instance = Context(dictionary) data = {} # construct date dictory for d in context_instance: data.update(d) # return string return mako_temp.render_unicode( **data) # .replace('\t','').replace('\n','').replace('\r','')
def index(request): recent_jobs = Job.objects.select_related('images').filter( is_featured=True, ).order_by('-date')[:4] departments = Department.objects.filter( name__in = ['Environmental','Architecture & Engineering',] ).order_by('name')[:3] context = { 'nav_selected': 'home', 'recent_jobs': recent_jobs, 'departments': departments, } return render_to_response( template_name = 'index.html', dictionary = Context(context), context_instance = RequestContext(request), )
def send_message(request): if request.method == 'POST': user = request.POST.get('user') up = UserProfile.objects.get(user__username=user) notification = Notification.objects.create( message=request.POST.get('message'), sender=UserProfile.objects.get(user=request.user), recipient=up, type="Message") notification_template = loader.get_template('notification.html') c = Context({'notification': notification}) message = notification_template.render(c) return HttpResponse( simplejson.dumps({ 'user': request.user.username, 'recipient': user, 'message': message, 'type': 'message' })) return HttpResponse('Not here!')
def get_context(context_dict=None, current_app='', request_path=None, user_data=None): user = user_data if hasattr(user_data, '_meta') else MockUser(user_data) context_dict = context_dict or {} context_updater = { 'request': MockRequest(request_path, user), } if user_data: context_updater['user'] = user context_dict.update(context_updater) context = Context(context_dict) contribute_to_context(context, current_app) return context
def _get_block_names(template): """ Générer la liste des noms de blocs d'un template :rtype: generator<string> """ nodelist = template.template.nodelist extendlist = nodelist.get_nodes_by_type(ExtendsNode) if len(extendlist) > 0: for block in extendlist[0].blocks: yield block parent_template = get_template(extendlist[0].parent_name.resolve( Context({}))) for item in Template._get_block_names(parent_template): yield item else: nodelist = template.template.nodelist for node in nodelist: if isinstance(node, BlockNode): yield node.name
def start_tag_following( follower_user, tag): if False == ( tag in follower_user.userprofile.followed_discussions_tags.all()): follower_user.userprofile.followed_discussions_tags.add( tag.name) follower_user.userprofile.save() all_users_visiabale_for_a_user_list = get_all_users_visiabale_for_a_user_list(follower_user) # already_following_users = [] # for user in all_users_visiabale_for_a_user_list: # if name in user.userprofile.followed_discussions_tags.names(): # already_following_users.append(user) t = Template(""" {{follower_user.get_full_name|default:follower_user.username}} גם התחיל/ה לעקוב אחרי {{name}} """) subject = t.render(Context({"follower_user": follower_user, "name" : tag.name})) html_message = render_to_string("coplay/user_follow_tag_email_update.html", {'ROOT_URL': kuterless.settings.SITE_URL, 'follower_user': follower_user, 'html_title': string_to_email_subject(subject), 'details': subject, 'tag': tag}) # with open( "output.html" , "w") as debug_file: # debug_file.write(html_message) for user in all_users_visiabale_for_a_user_list: if tag in user.userprofile.followed_discussions_tags.all(): if user.email != None and user.userprofile.recieve_updates: send_html_message(subject, html_message, '*****@*****.**', [user.email]) post_update_to_user(user.id, header = string_to_email_subject(subject), content = subject, sender_user_id = follower_user.id, details_url = reverse('coplay:discussion_tag_list', kwargs={'pk': tag.id}))
def discussion_add_task(discussion, responsible, goal_description, target_date, max_inactivity_seconds=MAX_INACTIVITY_SECONDS): if not discussion.can_user_access_discussion(responsible): return None, "user cannot access discussion" if target_date <= timezone.now(): return None, "target date should be in the future" tasks_list = Task.objects.all().filter(responsible=responsible, goal_description= goal_description, parent=discussion) if tasks_list.count() != 0: return None, "task already exsist" task = discussion.task_set.create(parent=discussion, responsible=responsible, goal_description=goal_description, target_date=target_date) task.full_clean() task.save() discussion.unlock(max_inactivity_seconds) discussion.save() #verify that the entire discussion is considered updated start_discussion_following( discussion, responsible) t = Template(""" {{task.responsible.get_full_name|default:task.responsible.username}} הבטיח/ה ש :\n "{{task.goal_description}} "\n עד {{task.target_date | date:"d/n/Y H:i"}} """) success, error_string = start_discussion_following( discussion, responsible) if success == False: return None, error_string trunkated_subject_and_detailes = t.render(Context({"task": task})) discussion_task_email_updates(task, trunkated_subject_and_detailes, responsible, trunkated_subject_and_detailes) return task, None
def modality_providers(request, modality_id, zipcode=None): if zipcode: try: zipcode_object = Zipcode.objects.get(code=zipcode) except Zipcode.DoesNotExist: return HttpResponse("Could not find Zipcode " + zipcode) request.session['point'] = zipcode_object.point zipcode = zipcode_object.code request.session['zipcode'] = zipcode else: zipcode = request.session.get('zipcode', None) if not zipcode: t = loader.get_template("modality/modality_get_zipcode.html") return HttpResponse(t.render(Context({"modality_id": modality_id}))) NUM_PROVIDERS = 20 try: modality = Modality.objects_approved.get(pk=modality_id) except Modality.DoesNotExist: return HttpResponse("Could not find Modality " + modality_id) providers, more = get_healers_geosearch(request, NUM_PROVIDERS, modality_id=modality_id) provider_count = len(providers) # if provider_count < NUM_PROVIDERS: # providers = set(list(providers) + list(Healer.objects.filter(modality=modality_id)[:NUM_PROVIDERS-provider_count])) providers = [p.user for p in providers] show_more = provider_count == NUM_PROVIDERS # just approximate for now return render_to_response("modality/modality_providers.html", { "modality": modality, "user": request.user, "providers": providers, "show_more_link": show_more, "zipcode": zipcode })
def write_odt_to_stream(stream, template_path, context={}): """ Takes ODT template on given path, fills it with context and writes the result to stream. :param stream: Stream-like object to write to :param template_path: Full path to ODT template :param context: Context that will be passed to template when rendering """ c = Context() for key, value in context.items(): if callable(value): c[key] = value() else: c[key] = value # default mimetype mimetype = 'application/vnd.oasis.opendocument.text' # ODF is just a zipfile input = zipfile.ZipFile(template_path, "r") output = zipfile.ZipFile(stream, "a") # go through the files in source for zi in input.filelist: out = input.read(zi.filename) # wait for the only interesting file if zi.filename == 'content.xml': # un-escape the quotes (in filters etc.) t = Template(out.replace('"', '"')) # render the document out = t.render(c) elif zi.filename == 'mimetype': # mimetype is stored within the ODF mimetype = out if type(out) != type('a'): out = encoding.smart_str(out, encoding='utf-8', strings_only=True, errors='strict') if out: output.writestr(zi.filename, out) output.close() return mimetype
def discussion_add_decision(discussion, user, content = None): if content == None: return None, 'No content' if not discussion.is_active(): return None, "discussion is not active" if user != discussion.owner: return None, "only discussion add a desicion" if Decision.objects.filter( parent = discussion, content = content).count() != 0: return None, "decision already exists" decision = Decision(parent=discussion, content=content) # print vars(decision) # decision.full_clean() decision.save() discussion.save() #verify that the entire discussion is considered updated success, error_string = start_discussion_following( discussion, user) if success == False: return None, error_string t = Template(""" {{decision.parent.owner.get_full_name|default:decision.parent.owner.username}} מבקש/ת שתצביע/י על :\n "{{decision.content}} "\nלהצבעה צריך להיכנס אל הפעילות המלאה... """) trunkated_subject_and_detailes = t.render(Context({"decision": decision})) discussion_email_updates(discussion, trunkated_subject_and_detailes, user, trunkated_subject_and_detailes, "#Decisions") user_post_a_decision_for_vote_regarding_his_own_discussion( user, decision.get_absolute_url()) return decision, None
def render(self, form, fields): contexts = tuple() for inline_field in self.inline_fields: if isinstance(inline_field, BaseField): contexts = contexts + (inline_field.get_context(form, fields), ) else: contexts = contexts + (inline_field, ) help = _merge_field(contexts, 'help_text') errors = _merge_field(contexts, 'errors') template = self.get_template() return template.render( Context({ 'fields': contexts, 'label': self.label, 'help': help, 'errors': errors, 'help_inline': help_inline }))
def mail_coord(hyperlink, mail_header, name, template, mail, password=""): print "mail helper function here hey" mail_template = get_template(template) print mail_template salt = sha.new(str(random.random())).hexdigest()[:5] activation_key = sha.new(salt + name).hexdigest() print activation_key body = mail_template.render( Context({ 'coordname': name, 'SITE_URL': hyperlink, 'activationkey': activation_key, 'new_password': password })) send_mail(mail_header, body, '*****@*****.**', mail, fail_silently=False) success_message = "mail sent" return success_message
def render_listview(self, render_context=None): """ Renders the standard list view of the grid. This can be called from templates. """ try: if render_context is None: render_context = self._build_render_context() self.load_state(render_context) context = Context({ 'datagrid': self, 'is_paginated': self.page.has_other_pages(), 'results_per_page': self.paginate_by, 'has_next': self.page.has_next(), 'has_previous': self.page.has_previous(), 'page': self.page.number, 'last_on_page': self.page.end_index(), 'first_on_page': self.page.start_index(), 'pages': self.paginator.num_pages, 'hits': self.paginator.count, 'page_range': self.paginator.page_range, }) if self.page.has_next(): context['next'] = self.page.next_page_number() else: context['next'] = None if self.page.has_previous(): context['previous'] = self.page.previous_page_number() else: context['previous'] = None context.update(self.extra_context) context.update(render_context) return mark_safe(render_to_string(self.listview_template, context)) except Exception: trace = traceback.format_exc(); logging.error('Failed to render datagrid:\n%s' % trace, extra={ 'request': self.request, }) return mark_safe('<pre>%s</pre>' % trace)
def send_letter_email(request, grad_slug, letter_slug): letter = get_object_or_404(Letter, slug=letter_slug) grad = get_object_or_404(GradStudent, person=letter.student.person, slug=grad_slug, program__unit__in=request.units) if request.method == 'POST': form = LetterEmailForm(request.POST) if form.is_valid(): letter.set_email_body(form.cleaned_data['email_body']) letter.set_email_subject(form.cleaned_data['email_subject']) if 'email_cc' in form.cleaned_data: letter.set_email_cc(form.cleaned_data['email_cc']) letter.set_email_sent(timezone_today()) letter.save() return _send_letter(request, grad_slug, letter) else: email_template = letter.template.email_body() temp = Template(email_template) ls = grad.letter_info() text = temp.render(Context(ls)) form = LetterEmailForm(initial={'email_body': text, 'email_subject': letter.template.email_subject()}) return render(request, 'grad/select_letter_email_text.html', {'form': form, 'grad': grad, 'letter': letter})
def test_pdf(): data = ['Paco', 'Perico', 'Chuncha', 'Maria la loca', 'la vieja chismosa'] for i in range(3): data = data + data # print(len(data)) # tmplate = get_template('xhtml2pdf.html') tmplate = get_template('pdf.html') html = tmplate.render(Context({'nombres': data})) # html = tmplate.render(Context({})) # file = open('xhtml2pdf.pdf','w+b') file = open('test.pdf', 'w+b') pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8', link_callback=link_callback) file.seek(0) pdf = file.read() file.close() print(pdf)
def task_send_booking_nt_to_business(event): business = event.customer.business subject = "Reserva" from_email = settings.ADMIN_EMAIL to = business.contact_email() template = loader.get_template("base/booking/email/business_nt.html") domain = settings.CATERFULL_BASE_URL context = Context({'domain': domain, 'business': business, 'event': event}) html_content = template.render(context) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.content_subtype = "html" # msg.attach_alternative(html_content, "text/html") try: msg.send(fail_silently=False) return OK except SMTPException as e: return ERROR
def tester(request): payload = {'first_name': 'thomas'} to = ['*****@*****.**'] #email1 = EmailTextTest(payload) #email1.send(to) #email2 = EmailHtmlTest(payload) #email2.send(to) #email3 = EmailMarkdownTest(payload) #email3.send(to) email4 = EmailHtmlWithBaseTest(payload, force_update=True) email4.send(to) return HttpResponse( Template( '{% load debug_tags %}<pre>{{ request.path}}{{ request.META|dir}}</pre>' ).render(Context({'request': request})))
def render_to_string(template_name, dictionary=None, context_instance=None, def_name=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 render_nemo_template(t, context_instance, def_name)
def render(self, args): logger.debug('Calling override render for ' + __name__) template_instance = get_template(self.template) data = self.get_context() data.update(widget=self, user=self.user, hostname=args) servers = Server.objects.filter(deleted=False, hostname=args) if len(servers) > 0: my_server = servers[0] data.update(server=my_server) assigned_classes = [] if my_server and my_server.puppet_classes: for current_class in my_server.puppet_classes.order_by( 'name').all(): assigned_classes.append(current_class) data.update(server_classes=assigned_classes) assignable_classes = PuppetClass.objects.all().order_by('name') available_classes = list( set(assignable_classes) - set(assigned_classes)) data.update(available_classes=available_classes) return template_instance.render(Context(data))
def run(self, request, context): try: report = CreadocReport.objects.get(pk=context.report_id) except CreadocReport.DoesNotExist: raise ApplicationLogicException( (u'Шаблон отчетной формы с id={} отсутствует, ' u'возможно он был удален.').format(context.report_id)) template_url = report.url t = loader.get_template('viewer.html') ctx = Context() ctx['template_url'] = template_url # Перечисление шаблонных переменных ctx['variables'] = CR.variables() # Перечисление подключенных источников данных ctx['sources'] = CR.connected_sources(context.report_id, params=context.params) return HttpResponse(t.render(ctx))
def test_placeholder_tag(self): template = Template( "{% load placeholder_tags %}{% render_placeholder placeholder %}") ctx = Context() self.assertEqual(template.render(ctx), "") request = self.get_request('/') rctx = RequestContext(request) self.assertEqual(template.render(rctx), "") placeholder = Placeholder.objects.create(slot="test") rctx['placeholder'] = placeholder self.assertEqual(template.render(rctx), "") self.assertEqual(placeholder.cmsplugin_set.count(), 0) add_plugin(placeholder, "TextPlugin", settings.LANGUAGES[0][0], body="test") self.assertEqual(placeholder.cmsplugin_set.count(), 1) rctx = RequestContext(request) placeholder = self.reload(placeholder) rctx['placeholder'] = placeholder self.assertEqual(template.render(rctx).strip(), "test")
def get_context_processors_content(request): """ return the context_processors dict context """ context = Context() try: from django.utils.module_loading import import_string from django.template.context import _builtin_context_processors context_processors = _builtin_context_processors context_processors += tuple(settings.TEMPLATE_CONTEXT_PROCESSORS) cp_func_list = tuple(import_string(path) for path in context_processors) for processors in cp_func_list: context.update(processors(request)) except Exception, e: logger.error("Mako: get_context_processors_content:%s" % e) context = Context()
def new_act_published(sender, **kwargs): """ generates a record in newscache when an act is presented (inserted in our DB) the news is generate only when an act is created, not updated and when this happens outside the fixture loading phase below, a trick used to handle signals when loading fixtures, it is not used now, but it may be useful, for testing purposes # instance for subclass fix, while loading fixtures # see http://bit.ly/yimn9S and # https://code.djangoproject.com/ticket/13299 if kwargs.get('raw', False): instance = kwargs['instance'] generating_item = instance.__class__._default_manager.get(pk=instance.pk) else: generating_item = kwargs['instance'] """ # generates news only if not in raw mode (fixtures) # and for objects creation if not kwargs.get('raw', False) and kwargs.get('created', False): generating_item = kwargs['instance'] # create transition: act is presented generating_item.transition_set.create( act=generating_item.act_ptr, final_status=generating_item.STATUS.presented, transition_date=generating_item.presentation_date, ) # define context for textual representation of the news ctx = Context({}) # generate news in newscache News.objects.create(generating_object=generating_item, related_object=generating_item, priority=1, text=News.get_text_for_news( ctx, 'newscache/act_published.html'))
def student_view(self, context=None): """The main view of OpenAssessmentBlock, displayed when viewing courses. The main view which displays the general layout for Open Ended Assessment Questions. The contents of the XBlock are determined dynamically based on the assessment workflow configured by the author. Args: context: Not used for this view. Returns: (Fragment): The HTML Fragment for this XBlock, which determines the general frame of the Open Ended Assessment Question. """ # On page load, update the workflow status. # We need to do this here because peers may have graded us, in which # case we may have a score available. try: self.update_workflow_status() except AssessmentWorkflowError: # Log the exception, but continue loading the page logger.exception('An error occurred while updating the workflow on page load.') ui_models = self._create_ui_models() # All data we intend to pass to the front end. context_dict = { "title": self.title, "question": self.prompt, "rubric_criteria": self.rubric_criteria, "rubric_assessments": ui_models, "show_staff_debug_info": self.is_course_staff and not self.in_studio_preview, } template = get_template("openassessmentblock/oa_base.html") context = Context(context_dict) frag = Fragment(template.render(context)) frag.add_css(load("static/css/openassessment.css")) frag.add_javascript(load("static/js/openassessment.min.js")) frag.initialize_js('OpenAssessmentBlock') return frag
def init_tree( self, tree_alias: str, context: Context ) -> Tuple[Optional[str], Optional[List['TreeItemBase']]]: """Initializes sitetree in memory. Returns tuple with resolved tree alias and items on success. On fail returns (None, None). :param tree_alias: :param context: """ request = context.get('request', None) if request is None: if any(exc_info()): # Probably we're in a technical # exception handling view. So we won't mask # the initial exception with the one below. return None, None raise SiteTreeError( 'Sitetree requires "django.core.context_processors.request" template context processor to be active. ' 'If it is, check that your view pushes request data into the template.') if id(request) != id(self.current_request): self.init(context) # Resolve tree_alias from the context. tree_alias = self.resolve_var(tree_alias) tree_alias, sitetree_items = self.get_sitetree(tree_alias) if not sitetree_items: return None, None return tree_alias, sitetree_items
def run(self, lines): new_text = [] for line in lines: m = ATTACHMENT_RE.match(line) if m: attachment_id = m.group('id').strip() before = self.run([m.group('before')])[0] after = self.run([m.group('after')])[0] try: attachment = models.Attachment.objects.get( articles__current_revision__deleted=False, id=attachment_id, current_revision__deleted=False ) url = reverse('wiki:attachments_download', kwargs={'article_id': self.markdown.article.id, 'attachment_id':attachment.id,}) # The readability of the attachment is decided relative # to the owner of the original article. # I.e. do not insert attachments in other articles that # the original uploader cannot read, that would be out # of scope! article_owner = attachment.article.owner if not article_owner: article_owner = AnonymousUser() attachment_can_read = can_read( self.markdown.article, article_owner) html = render_to_string( "wiki/plugins/attachments/render.html", Context({ 'url': url, 'filename': attachment.original_filename, 'attachment_can_read': attachment_can_read, })) line = self.markdown.htmlStash.store(html, safe=True) except models.Attachment.DoesNotExist: line = line.replace(m.group(1), """<span class="attachment attachment-deleted">Attachment with ID #%s is deleted.</span>""" % attachment_id) line = before + line + after new_text.append(line) return new_text
def send(self, recipient, unsubscribe=False): from dceu2019.apps.ticketholders.views import get_unsubscribe_key domain = '127.0.0.1:8000' if settings.DEBUG else 'members.2019.djangocon.eu' email = recipient.email context = { 'email': recipient.email, 'domain': domain, 'site_name': domain, 'protocol': 'http' if settings.DEBUG else 'https', 'unsubscribe_key': get_unsubscribe_key(email), } body_template_source = self.template_content if unsubscribe: body_template_source += ( "\n" + "\n" + "Unsubscribe:\n{{ protocol }}://{{ site_name }}{% url 'newsletter_unsubscribe' email=email key=unsubscribe_key %}" ) else: body_template_source += ( "\n\n" + "You are receiving this email because you have a ticket to DjangoCon Europe 2019 or a user account on the members' website." ) body = Template(body_template_source).render(Context(context)) subject = self.subject subject = ''.join(subject.splitlines()) email_message = EmailMultiAlternatives(subject, body, "*****@*****.**", [email]) email_message.send(fail_silently=False) self.mark_sent(email)
def render_to_temporary_file(template, context, request=None, mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True): try: if django.VERSION < (1, 8): # If using a version of Django prior to 1.8, ensure ``context`` is an # instance of ``Context`` if not isinstance(context, Context): if request: context = RequestContext(request, context) else: context = Context(context) # Handle error when ``request`` is None content = template.render(context) else: content = template.render(context, request) except AttributeError: content = loader.render_to_string(template, context) content = smart_text(content) content = make_absolute_paths(content) try: # Python3 has 'buffering' arg instead of 'bufsize' tempfile = NamedTemporaryFile(mode=mode, buffering=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) except TypeError: tempfile = NamedTemporaryFile(mode=mode, bufsize=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) try: tempfile.write(content.encode('utf-8')) tempfile.flush() return tempfile except: # Clean-up tempfile if an Exception is raised. tempfile.close() raise
class PasswordResetForm(authforms.PasswordResetForm): def save(self, from_email, domain_override=None, email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, request=None): try: user = User.objects.get(email=self.cleaned_data['email']) site = Site.objects.get(name='TicketTracker') except Exception, e: raise ValidationError(e) ctx = Context({ 'email': user.email, 'domain': site.domain, 'site_name': site.name, 'uid': int_to_base36(user.id), 'user': user, 'token': token_generator.make_token(user), 'protocol': use_https and 'https' or 'http', }) text_body = loader.get_template( 'email/email_password_reset.txt').render(ctx) html_body = loader.get_template( 'email/email_password_reset.html').render(ctx) try: bcc = [] if hasattr(settings, 'EMAIL_LOG'): bcc.append(settings.EMAIL_LOG) email = EmailMultiAlternatives('Password reset for TicketTracker', text_body, settings.SERVER_EMAIL, [user.email], bcc) email.attach_alternative(html_body, 'text/html') email.send() except Exception, ex: pass # TODO: do something when SMTP fails, but do not draw an error page