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 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 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 submit_row(context): """ Displays the row of buttons for delete and save. """ 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) ctx = Context(context) ctx.update({ '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 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': show_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 submit_row(context): """ <<<<<<< HEAD Displays the row of buttons for delete and save. ======= Display the row of buttons for delete and save. >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 """ 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) ctx = Context(context) ctx.update({ '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 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': show_save, }) return ctx
def submit_row(context): """ Display the row of buttons for delete and save. """ 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) ctx = Context(context) ctx.update({ "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 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": show_save, }) return ctx
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 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 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 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 sphblog_showblogpost(context, post): ret = { 'post': post, 'blogpost': post.blogpostextension_set.get(), } 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 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(request, page): context = Context() context.update(csrf(request)) context['page'] = page template = "index.html" form = DocumentForm() return render_to_response(template, {'form': form}, context_instance=RequestContext(request))
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 render(self, context): thing = self.context_thing.resolve(context) try: template = loader.get_template(self.template_name % (thing.type,)) except TemplateDoesNotExist: template = loader.get_template(self.template_name % ("default",)) template_context = Context(dict_=context) template_context.update({ 'thing': thing }) return template.render(template_context)
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 = 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_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 custom_field(field, **kwargs): """Use crispy_forms as a base template for custom fields for forms""" template_path = '%s/field.html' % TEMPLATE_PACK label = kwargs.get('label', True) context = Context({ 'field': field, 'form_show_errors': True, 'form_show_labels': bool(label) }) if isinstance(label, str): field.label = label columns = kwargs.get('cols', False) if columns: label_width = kwargs.get('label_width', 4) context.update({ 'label_class': 'col-lg-{}'.format(label_width), 'field_class': 'col-lg-{}'.format(12 - label_width) }) if kwargs.get('inline'): context.update({'inline_class': 'inline'}) if kwargs.get('datepicker'): context.update({'field_class': context['field_class'] + ' datepicker'}) append = kwargs.get('append') if append: context.update({'crispy_appended_text': append}) template_path = '%s/layout/prepended_appended_text.html' % TEMPLATE_PACK _template = loader.get_template(template_path) return _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 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_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 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 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 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 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 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 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 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 for i in settings.TEMPLATES: context_processors += tuple(i.get('OPTIONS', {}).get('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(u"Mako: get_context_processors_content error info:%s" % e) context = Context()
def render_xml(request, object_id): template_vars = {} t = loader.get_template('piecemaker/cms/content.xml') c = Context(template_vars) entries = Entry.published.all() object = PiecemakerLatestEntriesPlugin.objects.get(pk=object_id) if object.categories.count(): entries = entries.filter(categories__in=object.categories.all()) if object.authors.count(): entries = entries.filter(authors__in=object.authors.all()) if object.tags.count(): entries = TaggedItem.objects.get_union_by_model( entries, object.tags.all()) entries = entries.distinct()[:object.number_of_entries] c.update({'entries': entries, 'object': object}) return HttpResponse(t.render(c), mimetype="text/xml")
def render_toolbar(self, request): from cms.plugin_pool import plugin_pool from cms.utils.admin import get_admin_menu_item_context """ Renders the Toolbar. """ auth = request.user.is_authenticated() and request.user.is_staff edit = request.session.get('cms_edit', False) and auth page = request.current_page move_dict = [] if edit and page: template = get_template_from_request(request) placeholders = get_placeholders(template) for placeholder in placeholders: d = {} name = cms_settings.CMS_PLACEHOLDER_CONF.get("%s %s" % (page.get_template(), placeholder), {}).get("name", None) if not name: name = cms_settings.CMS_PLACEHOLDER_CONF.get(placeholder, {}).get("name", None) if not name: name = placeholder d['name'] = title(name) plugins = plugin_pool.get_all_plugins(placeholder, page) d['plugins'] = [] for p in plugins: d['plugins'].append(p.value) d['type'] = placeholder move_dict.append(d) data = safe(simplejson.dumps(move_dict)) else: data = {} if auth and page: context = get_admin_menu_item_context(request, page, filtered=False) else: context = Context() context.update({ 'auth':auth, 'page':page, 'templates': cms_settings.CMS_TEMPLATES, 'auth_error':not auth and 'cms_username' in request.POST, 'placeholder_data':data, 'edit':edit, 'CMS_MEDIA_URL': cms_settings.CMS_MEDIA_URL, }) from django.core.context_processors import csrf context.update(csrf(request)) return render_to_string('cms/toolbar/toolbar.html', context )
def create_notification(related_object, template_filename, user_to, user_from = None, **kwargs): u""" Create notification to user_to by template. Attribute: related_object - object which related to notification template_filename - message template filename at notifications/template_notifications/. template should include block label and body, used as message subject and body user_to - User created notification send to kwargs - this dict will be thrown to template as context. Notice: context by default includes user_from and user_to, so you can call it in template as {{ user_from }} or {{ user_to }}. user_from is by default User whose pk=1. Usage: create_notification(message_instance, 'new_message.txt', instance.user_to, user_from=instance.user_from) """ if not user_from: user_from = User.objects.get(pk=1) template_path = os.path.join('notifications/template_notifications', template_filename) template = get_template(template_path) if template: create_object_dict = {'user_from' : user_from, 'user_to' : user_to, 'content_type' : ContentType.objects.get_for_model(related_object), 'object_id' : related_object.pk} context = Context(create_object_dict) context.update({'object':related_object}) context.update(kwargs) if len(template.nodelist): for block in template.nodelist: if isinstance(block, BlockNode) and block.name == 'label': create_object_dict.update({'label' : block.render(context)}) if isinstance(block, BlockNode) and block.name == 'body': create_object_dict.update({'body' : block.render(context)}) notification = Notification.objects.create(**create_object_dict) notification.save() else: print "create_notification: template not found"
def render_to_response(self, template_name, extra_context={}): """ Renders a template containing this datagrid as a context variable. """ render_context = self._build_render_context() self.load_state(render_context) # If the caller is requesting just this particular grid, return it. if self.request.GET.get('gridonly', False) and \ self.request.GET.get('datagrid-id', None) == self.id: return self.render_listview_to_response( render_context=render_context) context = Context({'datagrid': self}) context.update(extra_context) context.update(render_context) return render_to_response(template_name, context)
def render_to_response(request, template, lookup, data=None, context=None): template = lookup.get_template(template) if data is None: data = {} if context is None: context = Context(data) else: context.update(data) tmpl_data = {} for d in context: tmpl_data.update(d) tmpl_data['reverse'] = reverse try: return HttpResponse(template.render(**tmpl_data)) except: if settings.DEBUG: return HttpResponse(exceptions.html_error_template().render()) raise
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_add_another = context.get("show_save_and_add_another", 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_add_another = (has_add_permission and not is_popup and (not save_as or add) and can_save and show_save_and_add_another) 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": can_save_and_add_another, "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 render_to_response(self, template_name, extra_context={}): """ Renders a template containing this datagrid as a context variable. """ render_context = self._build_render_context() self.load_state(render_context) # If the caller is requesting just this particular grid, return it. if self.request.GET.get('gridonly', False) and \ self.request.GET.get('datagrid-id', None) == self.id: return self.render_listview_to_response( render_context=render_context) context = Context({ 'datagrid': self }) context.update(extra_context) context.update(render_context) return render_to_response(template_name, context)
def ajax_task_add(request): """ Ajax call to create a new task. @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 form data from POST (if available) form_data = None if request.method == 'POST': form_data = request.POST # create task form task_form = TaskForm(UserProfile=request.user.get_profile(), 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': 'Create task', }) # 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 submit_row(context): """ Displays the row of buttons for delete and save. """ 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) ctx = Context(context) ctx.update({ '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 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': show_save, }) return ctx
def my_submit_row(context): """ Display the row of buttons for delete and save. """ 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) ctx = Context(context) ctx.update({ 'show_delete_link': (not is_popup and context['has_delete_permission'] and change and context.get('show_delete', True) and context.get('can_update', False)), #'show_save_as_new': not is_popup and change and save_as, 'show_save_as_new': False, #'show_save_and_add_another': ( # context['has_add_permission'] and not is_popup and # (not save_as or context['add']) #), 'show_save_and_add_another': False, #'show_save_and_continue': not is_popup and context['has_change_permission'] and show_save_and_continue, 'show_save_and_continue': False, 'show_save': False, 'show_update': context.get('can_update', False), 'show_upauth': context.get('can_upauth', False), 'show_bzauth': context.get('can_bzauth', False), }) return ctx
def get_context(self): """ Get the Context object for this message. Try to decode the body as a JSON and load into context if ``self.service.allow_json_body`` is ``True``. """ context = Context() context["subject"] = self.subject context["body"] = self.body if self.service.json_body_policy in [ self.service.PERMIT, self.service.REQUIRE ]: try: context.update(json.loads(self.body)) except json.JSONDecodeError: # body is not a JSON pass except TypeError: # top level JSON is not an object pass elif self.service.json_body_policy == self.service.FORBID: pass # do not attempt to load body as JSON into context else: raise ValueError( "json_body_policy is not valid (bad value {} for obj {})". format(self.service.json_body_policy, self.service.pk)) return context
def render(self, original_context): context = Context() context.update(original_context) slug = self.generate_slug(self.slug, context) related_model = self.resolve_model_for_label(self.modelname, context) # Get the generic and related object generic_object, related_object = self.get_content_object(related_model, slug) admin_url = self.generate_admin_link(related_object, context) # if "into" is provided, store the related object into this variable if self.store_in_object: into_var = self.resolve(self.store_in_object, context) update_dict = { into_var: related_object, "%s_generic_object" % into_var: generic_object, "%s_admin_url" % into_var: admin_url, } context.update(update_dict) return u'' # Add the model instances to the current context update_dict = { 'generic_object': generic_object, 'object': related_object, 'admin_url': admin_url, } context.update(update_dict) # Resolve the template(s) template_paths = [] if self.template_path: template_paths.append(self.resolve(self.template_path, context)) template_paths.append('%s/%s/flatblock.html' % \ tuple(self.resolve(self.modelname, context).lower().split("."))) try: t = select_template(template_paths) except: if settings.TEMPLATE_DEBUG: raise return u'' content = t.render(context) # Set content as variable inside context, if variable_name is given if self.variable_name: context[self.resolve(self.variable_name, context)] = content return u'' return content
def private_context_wrapper(context, *args, **kwargs): c = Context(context) rc = f(c, *args, **kwargs) c.update(rc) return c
def paginate(context, window=DEFAULT_WINDOW, hashtag=''): """ Renders the ``pagination/pagination.html`` template, resulting in a Digg-like display of the available pages, given the current page. If there are too many pages to be displayed before and after the current page, then elipses will be used to indicate the undisplayed gap between page numbers. Requires one argument, ``context``, which should be a dictionary-like data structure and must contain the following keys: ``paginator`` A ``Paginator`` or ``QuerySetPaginator`` object. ``page_obj`` This should be the result of calling the page method on the aforementioned ``Paginator`` or ``QuerySetPaginator`` object, given the current page. This same ``context`` dictionary-like data structure may also include: ``getvars`` A dictionary of all of the **GET** parameters in the current request. This is useful to maintain certain types of state, even when requesting a different page. """ try: paginator = context['paginator'] page_obj = context['page_obj'] page_range = paginator.page_range # Calculate the record range in the current page for display. records = {'first': 1 + (page_obj.number - 1) * paginator.per_page} records['last'] = records['first'] + paginator.per_page - 1 if records['last'] + paginator.orphans >= paginator.count: records['last'] = paginator.count # First and last are simply the first *n* pages and the last *n* pages, # where *n* is the current window size. first = set(page_range[:window]) last = set(page_range[-window:]) # Now we look around our current page, making sure that we don't wrap # around. current_start = page_obj.number - 1 - window if current_start < 0: current_start = 0 current_end = page_obj.number - 1 + window if current_end < 0: current_end = 0 current = set(page_range[current_start:current_end]) pages = [] # If there's no overlap between the first set of pages and the current # set of pages, then there's a possible need for elusion. if len(first.intersection(current)) == 0: first_list = list(first) first_list.sort() second_list = list(current) second_list.sort() pages.extend(first_list) diff = second_list[0] - first_list[-1] # If there is a gap of two, between the last page of the first # set and the first page of the current set, then we're missing a # page. if diff == 2: pages.append(second_list[0] - 1) # If the difference is just one, then there's nothing to be done, # as the pages need no elusion and are correct. elif diff == 1: pass # Otherwise, there's a bigger gap which needs to be signaled for # elusion, by pushing a None value to the page list. else: pages.append(None) pages.extend(second_list) else: unioned = list(first.union(current)) unioned.sort() pages.extend(unioned) # If there's no overlap between the current set of pages and the last # set of pages, then there's a possible need for elusion. if len(current.intersection(last)) == 0: second_list = list(last) second_list.sort() diff = second_list[0] - pages[-1] # If there is a gap of two, between the last page of the current # set and the first page of the last set, then we're missing a # page. if diff == 2: pages.append(second_list[0] - 1) # If the difference is just one, then there's nothing to be done, # as the pages need no elusion and are correct. elif diff == 1: pass # Otherwise, there's a bigger gap which needs to be signaled for # elusion, by pushing a None value to the page list. else: pages.append(None) pages.extend(second_list) else: differenced = list(last.difference(current)) differenced.sort() pages.extend(differenced) to_return = Context() to_return.update(context) to_return.update({ 'MEDIA_URL': settings.MEDIA_URL, 'pages': pages, 'records': records, 'page_obj': page_obj, 'paginator': paginator, 'hashtag': hashtag, 'is_paginated': paginator.count > paginator.per_page, }) if 'request' in context: getvars = context['request'].GET.copy() if 'page' in getvars: del getvars['page'] if len(getvars.keys()) > 0: to_return.update({'getvars': '&%s' % getvars.urlencode()}) else: to_return.update({'getvars': ''}) return to_return except KeyError, AttributeError: return {}
def render(self, context, instance, placeholder): request = context['request'] contact_form = instance.form FormClass = contact_form.get_form_class() my_context = Context({ 'placeholder': placeholder, 'contact_form': contact_form, 'form_instance': FormClass(), 'current_page': request.current_page, 'page': request.current_page, }) if request.method == 'POST' and "contactform_id" in request.POST \ and request.POST['contactform_id'] == str(contact_form.id): # process the submitted form form = FormClass(request.POST, request.FILES) if form.is_valid(): site = Site.objects.get_current() try: from siteinfo.models import SiteSettings contact = SiteSettings.objects.get_current() except: contact = None subject = u"[%s] %s" % (site.domain, _(u"Contact form sent")) print site.domain # render fields rows = '' files = [] to_pickle = {} for field in contact_form.field_set.all(): field_label = slugify(field.get_label()) value = form.cleaned_data[field_label] if isinstance(value, bool): value = yesno(value, u"%s,%s" % (_('yes'), _('no')),) if field.field_type == 'FileField': if field_label in request.FILES: this_file = request.FILES[field_label] if this_file.size > 10240: # check if file is bigger than 10 MB (which is not good) files.append(this_file) rows += u"%s: %s\n" % (form.fields[field_label].label, value) to_pickle[unicode(field_label)] = unicode(value) # use the verbose fieldname instead #to_pickle[form.fields[field_label].label] = value #pprint(to_pickle) message_context = Context({ 'site': site, 'form': form, 'contact_form': contact_form, 'rows': rows, 'sender_ip': request.META['REMOTE_ADDR'], 'form_url': request.build_absolute_uri(), }, autoescape=False) text_template = loader.get_template('dbform/form_email.txt') text_content = text_template.render(message_context) recipient_list = [recipient['email'] for recipient in contact_form.recipients.values('email')] bcc = [] if contact_form.cc_managers: bcc += [manager[1] for manager in settings.MANAGERS] if contact_form.cc_site_contact and contact: bcc += [contact.email] message = EmailMessage(subject=subject, body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=recipient_list, bcc=bcc) for file in files: message.attach(file.name, file.read(2621440), file.content_type) message.send() my_context.update({ 'form_instance': form, 'success': mark_safe(contact_form.success_message.strip() or _("Your request has been submitted. We will process it as soon as possible.")), }) # save message to db for later reference submission = FormSubmission( form=contact_form, sender_ip=request.META['REMOTE_ADDR'], form_url=request.build_absolute_uri(), language=contact_form.language, form_data=text_content, form_data_pickle=to_pickle) submission.save() else: my_context.update({ 'form_instance': form, 'contact_form': contact_form, }) return my_context
def render(self, context): page = context[self.page] try: contact_form = page.contactform_set.get() request = context['request'] except: # ContactForm.DoesNotExist or "django.core.context_processors.request" is not in default context processors return "" FormClass = contact_form.get_form_class() my_context = Context( { 'contact_form': contact_form, 'form_instance': FormClass(), # 'current_page': page, # 'page': page, }, autoescape=context.autoescape) if request.method == 'POST' and "contactform_id" in request.POST \ and request.POST['contactform_id'] == str(contact_form.id): # process the submitted form form = FormClass(request.POST, request.FILES) if form.is_valid(): site = Site.objects.get_current() try: from siteinfo.models import SiteSettings contact = SiteSettings.objects.get_current() except: contact = None subject = _(u"[%s] Contact form sent") % (site.domain) # render fields rows = '' files = [] for field in contact_form.field_set.all(): field_label = slugify(field.get_label()) value = form.cleaned_data[field_label] if isinstance(value, bool): value = yesno( value, u"%s,%s" % (_('yes'), _('no')), ) if field.field_type == 'FileField': if field_label in request.FILES: this_file = request.FILES[field_label] if this_file.size > 10240: # check if file is bigger than 10 MB (which is not good) files.append(this_file) rows += u"%s: %s\n" % (form.fields[field_label].label, value) message_context = Context( { 'site': site, 'form': form, 'contact_form': contact_form, 'rows': rows, }, autoescape=False) text_template = loader.get_template('dbform/form_email.txt') text_content = text_template.render(message_context) recipient_list = [ recipient['email'] for recipient in contact_form.recipients.values('email') ] bcc = [] if contact_form.cc_managers: bcc += [manager[1] for manager in settings.MANAGERS] if contact_form.cc_site_contact and contact: bcc += [contact.email] message = EmailMessage(subject=subject, body=text_content, from_email=settings.DEFAULT_FROM_EMAIL, to=recipient_list, bcc=bcc) for file in files: message.attach(file.name, file.read(2621440), file.content_type) message.send() my_context.update({ 'form_instance': form, 'success': contact_form.success_message.strip() or _("Your request has been submitted. We will process it as soon as possible." ), }) else: my_context.update({ 'form_instance': form, 'dbform': contact_form, }) return loader.render_to_string("dbform/form.html", my_context)
log.write("Found 'compress' tags in:\n\t" + "\n\t".join((t.template_name for t in compressor_nodes.keys())) + "\n") log.write("Compressing... ") count = 0 results = [] offline_manifest = SortedDict() for template, nodes in compressor_nodes.iteritems(): context = Context(settings.COMPRESS_OFFLINE_CONTEXT) template._log = log template._log_verbosity = verbosity for node in nodes: context.push() compiled_node = env.compile(jinja2.nodes.Template(node.body)) context.update(jingo.register.env.globals) context.update(jingo.register.env.filters) key = get_offline_hexdigest( Template.from_code(jingo.register.env, compiled_node, {}).render(context)) try: context['compress_forced'] = True compiled_node = env.compile(jinja2.nodes.Template([node])) result = Template.from_code(env, compiled_node, {}).render(context) except Exception, e: raise CommandError("An error occured during rendering %s: " "%s" % (template.template_name, e)) offline_manifest[key] = result context.pop()