def causes(request): c = Context(defaultContext) # assert False c.update({ 'current_menu_choice': 'causes' }) return render_to_response('causes.html', c)
def _render(self, context, form, helper, caller): if helper is None: helper = crispy.FormHelper() if not hasattr(form, 'helper') else form.helper is_formset = isinstance(form, BaseFormSet) node_context = Context(context.get_all()) node = crispy.BasicNode(form, helper) context_dict = node.get_response_dict(helper, node_context, is_formset) node_context.update(context_dict) if helper and helper.layout: if not is_formset: form.form_html = helper.render_layout(form, node_context, template_pack=crispy.TEMPLATE_PACK) else: forloop = crispy.ForLoopSimulator(form) for f in form.forms: node_context.update({'forloop': forloop}) form.form_html = helper.render_layout(f, node_context, template_pack=crispy.TEMPLATE_PACK) forloop.iterate() if is_formset: context_dict.update({'formset': form}) else: context_dict.update({'form': form}) context = Context(context_dict) if context['is_formset']: template = crispy.whole_uni_formset_template(crispy.TEMPLATE_PACK) else: template = crispy.whole_uni_form_template(crispy.TEMPLATE_PACK) return template.render(context)
def render(self, name, value, attrs=None, extra_context={}): #print "BEGIN RENDER %s: %s" % (name, value) template = loader.select_template(['widgetry/fk_lookup/widget.html']) search_url = reverse('widgetry-search') admin_media_prefix = getattr(settings, 'ADMIN_MEDIA_PREFIX', None) or ''.join([settings.STATIC_URL, 'admin/']) # the label if value: label = self.label_for_value(value) else: label = u'' # allow the object browsing popup if (self.show_edit): enable_edit = u'true' else: enable_edit = u'false' if self.content_type: content_type_id = self.content_type.pk if value is None: value = '' else: value = str(value) content_type_info = self.content_type_info content_type_info_json = simplejson.dumps(content_type_info) context = Context(locals()) context.update(extra_context) r = template.render(context) return r
def user_login(request): error = '' #Read next url to be redirected to try: redirect_to = request.REQUEST["next"] except KeyError: redirect_to = "/portcullis/user_streams/" if request.method == 'POST': user = authenticate(username=request.POST["username"], password=request.POST["password"]) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(redirect_to) else: error = "Account disabled" else: error = "Invalid login"; t = loader.get_template('login.html'); c = Context({'user':request.user,'error':error,"redirect_to":redirect_to}) c.update(csrf(request)); return HttpResponse(t.render(c))
def deliver(self, recipient, sender, notice_type, extra_context): """ Deliver a notice to a User DefaultBackend.deliver will send to the receiver (a User) a notification of an action triggered by some other User on an Action or on some article related to it """ # Inspired from django-notification-brosner.backends.EmailBackend # 1. Get formatted messages context = Context({"recipient": recipient, "sender": sender, "notice": ugettext(notice_type.display)}) context.update(extra_context) messages = self.get_formatted_messages(("short.txt", "full.txt"), notice_type.label, context) # 2. Render them with on-site site-wide notification templates subject = render_to_string( "notification/on_site_notice_subject.txt", {"message": messages["short.txt"]}, context ) text = render_to_string("notification/on_site_notice_text.txt", {"message": messages["full.txt"]}, context) notice_text = u"%s%s" % (subject, text) # 3. Deliver notice = save new notice for User 'recipient' from notification.models import Notice Notice.objects.create(recipient=recipient, message=notice_text, notice_type=notice_type, on_site=True)
def render_to_string(template_name, dictionary, context=None, namespace='main'): # see if there is an override template defined in the microsite template_name = microsite.get_template_path(template_name) context_instance = Context(dictionary) # add dictionary to context_instance context_instance.update(dictionary or {}) # collapse context_instance to a single dictionary for mako context_dictionary = {} context_instance['settings'] = settings context_instance['EDX_ROOT_URL'] = settings.EDX_ROOT_URL context_instance['marketing_link'] = marketing_link context_instance['is_any_marketing_link_set'] = is_any_marketing_link_set context_instance['is_marketing_link_set'] = is_marketing_link_set # In various testing contexts, there might not be a current request context. request_context = get_template_request_context() if request_context: for item in request_context: context_dictionary.update(item) for item in context_instance: context_dictionary.update(item) if context: context_dictionary.update(context) # "Fix" CSRF token by evaluating the lazy object KEY_CSRF_TOKENS = ('csrf_token', 'csrf') for key in KEY_CSRF_TOKENS: if key in context_dictionary: context_dictionary[key] = unicode(context_dictionary[key]) # fetch and render template template = lookup_template(namespace, template_name) return template.render_unicode(**context_dictionary)
def render_to_string(template_name, dictionary, context=None, namespace='main'): # see if there is an override template defined in the microsite template_name = microsite.get_template_path(template_name) context_instance = Context(dictionary) # add dictionary to context_instance context_instance.update(dictionary or {}) # collapse context_instance to a single dictionary for mako context_dictionary = {} context_instance['settings'] = settings context_instance['EDX_ROOT_URL'] = settings.EDX_ROOT_URL context_instance['marketing_link'] = marketing_link # In various testing contexts, there might not be a current request context. if edxmako.middleware.REQUEST_CONTEXT.context is not None: for d in edxmako.middleware.REQUEST_CONTEXT.context: context_dictionary.update(d) for d in context_instance: context_dictionary.update(d) if context: context_dictionary.update(context) # fetch and render template template = lookup_template(namespace, template_name) return template.render_unicode(**context_dictionary)
def render(self, context=None, request=None): if context is None: context = {} if request is not None: def _get_val(): token = get_token(request) if token is None: return 'NOTPROVIDED' else: return smart_text(token) context["request"] = request context["csrf_token"] = SimpleLazyObject(_get_val) # Support for django context processors for processor in self.backend.context_processors: context.update(processor(request)) if settings.TEMPLATE_DEBUG: from django.test import signals self.template.origin = Origin(self.template.filename) context_obj = Context(context) context_processors = {} if request is not None: for processor in self.backend.context_processors: context_processors[processor.__name__] = processor(request) context_obj.context_processors = context_processors signals.template_rendered.send(sender=self, template=self.template, context=context_obj) return self.template.render(context)
def django_render_block(template, block_name, context): # Create a Django Context. context_instance = Context(context) # Get the underlying django.template.base.Template object. template = template.template # Bind the template to the context. with context_instance.bind_template(template): # Before trying to render the template, we need to traverse the tree of # parent templates and find all blocks in them. parent_template = _build_block_context(template, context_instance) try: return _render_template_block(template, block_name, context_instance) except BlockNotFound: # The block wasn't found in the current template. # If there's no parent template (i.e. no ExtendsNode), re-raise. if not parent_template: raise # Check the parent template for this block. return _render_template_block( parent_template, block_name, context_instance)
def render(element, markup_classes): element_type = element.__class__.__name__.lower() if element_type == 'boundfield': add_input_classes(element) template = get_template("bootstrapform/field.html") context = Context({'field': element, 'classes': markup_classes, 'form': element.form}) else: has_management = getattr(element, 'management_form', None) if has_management: for form in element.forms: for field in form.visible_fields(): add_input_classes(field) template = get_template("bootstrapform/formset.html") context = Context({'formset': element, 'classes': markup_classes}) else: for field in element.visible_fields(): add_input_classes(field) template = get_template("bootstrapform/form.html") context = Context({'form': element, 'classes': markup_classes}) if django_version >= (1, 8): context = context.flatten() return template.render(context)
def deliver(self, recipient, sender, notice_type, extra_context): # TODO: require this to be passed in extra_context current_site = Site.objects.get_current() notices_url = "{0}://{1}{2}".format( DEFAULT_HTTP_PROTOCOL, str(Site.objects.get_current()), urlresolvers.reverse("notification_notices"), ) # update context with user specific translations context = Context({ "user": recipient, # Old compatible "recipient": recipient, "sender": sender, "notice": ugettext(notice_type.display), "notices_url": notices_url, "current_site": current_site, }) context.update(extra_context) messages = self.get_formatted_messages(( "notice.html", ), notice_type.label, context) from notification.models import Notice notice = Notice.objects.create( recipient=recipient, sender=sender, notice_type=notice_type, message=messages['notice.html'], on_site=True, )
def preBuild(site): global CASES # Build all the cases for case in site.pages(): if case.path.startswith(DIR): # Skip non html cases for obvious reasons if not case.path.endswith('.html'): continue # Parse headers and markdown body headers, body = parsePost(case.data()) # Build a context for each post caseContext = Context() caseContext.update(headers) caseContext['raw_body'] = body caseContext['path'] = case.path caseContext['date'] = parseDate(headers.get('date') or headers.get('created')) caseContext['url'] = case.absolute_final_url caseContext['tags'] = headers.get('tags') and [h.strip() for h in headers['tags'].split(',')] or [] caseContext['category'] = headers.get('category') and [h.strip() for h in headers['category'].split(',')] or [] CASES.append(caseContext) # Sort the cases by date CASES = sorted(CASES, key=lambda x: x['date']) CASES.reverse() indexes = range(0, len(CASES)) for i in indexes: if i+1 in indexes: CASES[i]['prev_post'] = CASES[i+1] if i-1 in indexes: CASES[i]['next_post'] = CASES[i-1]
def render_given_args(self, resolved_args, context_attrs): context = self._context # CHANGED: func -> cached_func _dict = cached_func(*resolved_args) t = context.render_context.get(self) if t is None: if isinstance(file_name, Template): t = file_name elif isinstance(getattr(file_name, 'template', None), Template): t = file_name.template elif not isinstance(file_name, six.string_types) and is_iterable(file_name): t = context.template.engine.select_template(file_name) else: t = context.template.engine.get_template(file_name) context.render_context[self] = t # CHANGED: new_context = context.new(_dict) to the following # five lines. We don't want to copy the context because it # might be a RequestContext, even if the tag's cache doesn't # depend on this user. This would be Very Bad; it could cause # the cache to leak data about one user to another user. So we # require using a plain Context, and copy a whitelisted set of # attrs over, rather than using copy(). new_context = Context(_dict) for attr, val in context_attrs.iteritems(): setattr(new_context, attr, val) new_context.render_context = copy(context.render_context) # CHANGED: removed copying the csrf_token over to the # new_context, because we should never do that. If you need a # csrf_token in an inclusion tag, you'll have to generate your # own with AJAX. return t.render(new_context)
def test_tagcloud(self): t = get_template('taggit_templatetags2/tagcloud_include.html') c = Context({'forvar': None}) t.render(c) self.assert_tags_equal(c.get("tags"), ["green"], False) self.assertEqual(c.get("tags")[0].name, "green") self.assertEqual(c.get("tags")[0].weight, 6.0)
def test_context_comparable(self): """ #21765 -- equality comparison should work """ test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} self.assertEqual(Context(test_data), Context(test_data)) a = Context() b = Context() self.assertEqual(a, b) # update only a a.update({'a': 1}) self.assertNotEqual(a, b) # update both to check regression a.update({'c': 3}) b.update({'c': 3}) self.assertNotEqual(a, b) # make contexts equals again b.update({'a': 1}) self.assertEqual(a, b)
def get_formatted_message(formats, notice_type, context, medium): """ Returns a dictionary with the format identifier as the key. The values are are fully rendered templates with the given context. """ if not isinstance(context, Context): context = Context(context or {}) protocol = 'https' if USE_SSL else 'http' current_site = Site.objects.get_current() base_url = u"%s://%s" % (protocol, unicode(current_site)) context.update({ 'base_url': base_url, 'site': current_site, }) format_templates = {} context = apply_context_processors(context) for format in formats: # conditionally turn off autoescaping for .txt extensions in format if format.endswith(".txt") or format.endswith(".html"): context.autoescape = False else: context.autoescape = True format_templates[format] = render_to_string(( 'notification/%s/%s/%s' % ( notice_type.template_slug, medium, format), 'notification/%s/%s' % (notice_type.template_slug, format), 'notification/%s/%s' % (medium, format), 'notification/%s' % format), context_instance=context) return format_templates
def test_model(self): t = Template(self.get_template("as taglist for 'testapp.BetaModel'")) c = Context({}) t.render(c) self.assert_tags_equal( c.get("taglist"), ["sweet", "green", "yellow"], False)
def index(request): loginerr = False logoutsuccess = False if request.GET.get("loginerr","false") == "true": loginerr = True if request.GET.get("logoutsuccess","false") == "true": logoutsuccess = True full_news_list = News.objects.all().order_by('-published_date') oldest_page = math.ceil(len(full_news_list) / 6.0) user = None logged_in = request.session.get('logged_in', False) oldest_page_newsboard = 0 if logged_in: user = User.objects.get(id=request.session.get('uid',0)) oldest_page_newsboard = math.ceil(len(user.pinned_news.all()) / 6.0) c = Context({ 'loginerr': loginerr, 'logoutsuccess': logoutsuccess, 'logged_in': request.session.get('logged_in', False), 'user': user, 'oldest_page_mostrecent': oldest_page, 'oldest_page_mostviewed': oldest_page, 'oldest_page_newsboard': oldest_page_newsboard, 'sidebarnews': full_news_list[:12], }) c.update(csrf(request)) return render_to_response("news.html", c)
def handle_extendsnode(extendsnode, block_context=None, original=None): """Create a copy of Node tree of a derived template replacing all blocks tags with the nodes of appropriate blocks. Also handles {{ block.super }} tags. """ if block_context is None: block_context = BlockContext() blocks = dict((n.name, n) for n in extendsnode.nodelist.get_nodes_by_type(BlockNode)) block_context.add_blocks(blocks) # Note: we pass an empty context when we find the parent, this breaks # inheritance using variables ({% extends template_var %}) but a refactor # will be needed to support that use-case with multiple offline contexts. context = Context() if original is not None: context.template = original compiled_parent = extendsnode.get_parent(context) parent_nodelist = compiled_parent.nodelist # If the parent template has an ExtendsNode it is not the root. for node in parent_nodelist: # The ExtendsNode has to be the first non-text node. if not isinstance(node, TextNode): if isinstance(node, ExtendsNode): return handle_extendsnode(node, block_context, original) break # Add blocks of the root template to block context. blocks = dict((n.name, n) for n in parent_nodelist.get_nodes_by_type(BlockNode)) block_context.add_blocks(blocks) block_stack = [] new_nodelist = remove_block_nodes(parent_nodelist, block_stack, block_context) return new_nodelist
def my_admin(request): if request.POST: print "post" if 'operation' in request.POST.keys(): if request.POST['operation']=='delete book': print "deleting book id " + request.POST['book'] #book.objects.filter("book_id=" + request.POST['book'] ).delete() book.objects.get(book_id=request.POST['book']).delete() elif request.POST['operation']=='edit book': return HttpResponseRedirect("/books/my_admin/modify_book/edit/" + request.POST['book'] + "/") elif request.POST['operation']=='new book': return HttpResponseRedirect("/books/my_admin/modify_book/add//") elif request.POST['operation']==u'purge books': print 'purging books' book.objects.all().delete() elif request.POST['operation']==u'import books': my_admin_load_BooksDB() #t = loader.get_template('my_admin.html') c = Context({ 'all_books': book.objects.all().order_by("title"), }) c.update(csrf(request)) # ... view code here return render_to_response("my_admin.html", c)
def render(self, context): # our main context storage = Context() # stash the whole context if needed if settings.KEEP_CONTEXT: storage.update(flatten_context(context)) # but check if there are variables specifically wanted for var_name in self.var_names: if var_name[0] in ('"', "'") and var_name[-1] == var_name[0]: var_name = var_name[1:-1] try: storage[var_name] = Variable(var_name).resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError( '"phased" tag got an unknown variable: %r' % var_name) # lastly return the pre phased template part return u'%(delimiter)s%(content)s%(pickled_context)s%(pickled_components)s%(delimiter)s' % { 'content': self.content, 'delimiter': settings.SECRET_DELIMITER, 'pickled_context': pickle_context(backup_csrf_token(context, storage)), 'pickled_components': pickle_components(self.components), }
def run(script, doc, output_file=None, options={}): """process a Django template file""" # this is needed to use the Django template system as standalone # I need to re-import the settings at every call because I have to # set the TEMPLATE_DIRS variable programmatically from django.conf import settings try: settings.configure(DEBUG=True, TEMPLATE_DEBUG=True, TEMPLATE_DIRS=(os.path.dirname(script),)) except EnvironmentError: pass from django.template import Context from django.template.loader import get_template # set up the Django context by using the default htmltmpl # datatype converters context = Context() context.update(tmpl.template_info(doc)) context["Config"] = config.planet_options() t = get_template(script) if output_file: reluri = os.path.splitext(os.path.basename(output_file))[0] context["url"] = urlparse.urljoin(config.link(), reluri) f = open(output_file, "w") ss = t.render(context) if isinstance(ss, unicode): ss = ss.encode("utf-8") f.write(ss) f.close() else: # @@this is useful for testing purposes, but does it # belong here? return t.render(context)
def shortify_url(request): if request.method == 'POST': context = Context({}) url = request.POST.get('url','') print "URL",url if not url: context['errors'] = 'No URL was supplied' # checking for the supplied url if js is off else: # the url has been supplied try: check_obj = URLtoHASH.objects.get(url=url) # checking if the url is already shoretened or not print "URL ALREADY EXISTS" hash_val = check_obj.hash_value except: # means the user entered a new url url_obj = URLtoHASH(url=url) # creating a new URL obj url_obj.save() # save to DB url_id = url_obj.id # getting the ID of the stored DB object print 'URL_ID',url_id hash_val = hashed_string(url_id) url_obj.hash_value = hash_val# saving the hashed value to the DB url_obj.save() # saving the changes to the DB print 'HASH_VALUE',hash_val shortened_url = urlparse.urlunparse(('http',HOSTNAME,hash_val,'','','')) context["success"] = shortened_url print shortened_url context.update(csrf(request)) return render_to_response('index.html',context)
def send_email_template(template, context, to, email_from=None, html=None): """ Renders an email template with this format: {% if subject %}Subject{% endif %} {% if message %}Email body{% endif %} context can be a dictionary or a template.Context instance """ from django.template.loader import render_to_string from django.template import Context if isinstance(context, dict): context = Context(context) if type(to) in [str, unicode]: to = [to] if not 'site' in context: # fallback site value context.update({'site': get_controller_site()}) #subject cannot have new lines subject = render_to_string(template, {'subject': True}, context).strip() message = render_to_string(template, {'message': True}, context) msg = EmailMultiAlternatives(subject, message, email_from, to) if html: html_message = render_to_string(html, {'message': True}, context) msg.attach_alternative(html_message, "text/html") msg.send()
def test_qurl_as(self): context = Context() Template( '{% load qurl %}' '{% qurl "http://sophilabs.com/?a=1" a=None as url %}' ).render(context) self.assertEqual(context.get('url'), 'http://sophilabs.com/')
def render_to_task(cmd, when="now"): context = Context({"cmd": cmd}) taskdir = os.path.join(settings.TASKMASTER_PATH, 'tasks') # Lock lock = open(os.path.join(settings.TASKMASTER_PATH, 'addlock')) flock(lock, LOCK_EX) try: tasks = os.listdir(os.path.join(settings.TASKMASTER_PATH, 'tasks')) except OSError: tasks = [] os.mkdir(os.path.join(settings.TASKMASTER_PATH, 'tasks'), 0755) tasks.sort(cmp=lambda x,y: cmp(int(x), int(y))) try: taskno = int(tasks[-1]) + 1 except IndexError: taskno = 1 # Write the task path = os.path.join(taskdir, str(taskno)) context.update({"path": path}) txt = TEMPLATE.render(context) #print "Writing to the path '%s' the following: %s" % (path, txt) h = open(path, 'w') h.write(txt) h.close() subprocess.call(["at", "-f", path, when]) # Unlock flock(lock, LOCK_UN) lock.close()
def send_mail(request, templates_name, recipient_list, context=None): u"""Proxy for sending emails.""" fail_silently = FAIL_SILENTLY auth_user = AUTH_USER auth_password = AUTH_PASSWORD connection = CONNECTION context = Context(context or {}) context.update({ 'protocol': 'https' if request.is_secure() else 'http', 'domain': get_current_site(request).domain, }) text_template = get_template('emails/{}.txt'.format(templates_name)) html_template = get_template('emails/{}.html'.format(templates_name)) bcc = list(get_administrators_emails().values()) connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently ) # required, if omitted then no emails from BCC are send headers = {'bcc': ','.join(bcc)} email = EmailMultiAlternatives( SUBJECTS[templates_name], text_template.render(context), FROM_ADDRESS, recipient_list, bcc, connection=connection, headers=headers ) email.attach_alternative(html_template.render(context), 'text/html') return email.send()
def get_context(): if engines is not None: context = Context() context.template = Template('') return context else: return {}
def __init__(self, team): Context.__init__(self) self['team'] = team self['rounds'] = [self.round_obj(x) for x in RoundAccess.objects.filter(team=team).order_by('id')] self['solved_metas'] = [x.metapuzzle for x in MetapuzzleSolve.objects.filter(team=team).order_by('id')] self['log_entries'] = [{"entry": x} for x in TeamLog.objects.filter(team=team).order_by('-id')] for entry in self['log_entries']: msg = entry['entry'].message if "[[" in msg: entry['protected_message'] = log_entry_protect.sub('[hidden]', msg) entry['unprotected_message'] = log_entry_protect.sub(r'\1', msg) # ----- 2014-specific ----- self['has_wl_access'] = (len(self['rounds']) > 2) try: self['gone_with_the_wind_released'] = PuzzleAccess.objects.filter(team=team, puzzle=Puzzle.objects.get(url='gone_with_the_wind')).exists() except: logger.exception('couldn\'t determine if gone_with_the_wind has been released') pass self['team_data'] = Y2014TeamData.objects.get(team=team) points = self['team_data'].points self['tickett'] = TRAIN_COST if points >= TRAIN_READY[2]: self['ticket'] = 0 self['tickett'] = None elif points < DRINK_READY[-1]: self['ticket'] = 0 elif points >= TRAIN_READY[1]: self['ticket'] = min(TRAIN_COST, max(0, points - TRAIN_READY[1])) elif points >= TRAIN_READY[0]: self['ticket'] = min(TRAIN_COST, max(0, points - TRAIN_READY[0])) else: self['ticket'] = min(TRAIN_COST, max(0, points - DRINK_READY[-1])) self['ticketx'] = self['ticket']*10/TRAIN_COST
def handle(self, *args, **options): for student in Student.objects.visible(): try: PdfFileReader(file("%s%s" % (s.MEDIA_ROOT, str(student.resume)), "rb"),) except Exception as e: try: student.deactivate() managers = [mail_tuple[1] for mail_tuple in s.MANAGERS] context = Context({ 'student_first_name': student.first_name, 'student_last_name': student.last_name, 'student_email': student.user.email }) context.update(get_basic_email_context()) subject = ''.join(render_to_string('email_admin_subject.txt', { 'message': "Faulty resume" }, context).splitlines()) body = render_to_string('faulty_resume_email_body.txt', context) send_email(subject, body, managers) except Exception as e: print e
continue feed = Feed() feed.title = article['t'] getContent(smth, articleparser, article['b'], article['gid'], feed, 0) getContent(smth, articleparser, article['b'], article['gid'], feed, 1) sumaryFeeds.append(feed) #write data f = open(archive + "/sm.data", "w") cPickle.dump(sumaryFeeds, f) f.close() #write to html t = Template(bookTemplate) c = Context({"sumaryFeeds": sumaryFeeds, "today": today}) renderdHtml = t.render(c) f = open(archive + "/sm.html", "w") f.write(renderdHtml.encode("utf8")) f.close() #uniq the feed #write to datebases previousThread = Thread.objects.filter(date=today) if len(previousThread) == 0: p = Thread.objects.create(location=archive + "sm.html", mobiLocation=archive + "sm.mobi") p.save() else: p = previousThread[0]
def test_view(request): template = Template(template_string=self.test_view_template) context = Context( dict_={'object': test_object, 'resolved_object': test_object} ) return HttpResponse(template.render(context=context))
def test_dictionary_and_context_instance_kwarg(self): self.assertEqual(render_to_string(self.template_name, dictionary={'obj': '1'}, context_instance=Context({'obj': '2'})), 'obj:1')
def test_context_instance_kwarg(self): self.assertEqual(render_to_string(self.template_name, context_instance=Context({'obj': 'test'})), 'obj:test')
def test_verbatim_tag05(self): template = Template(self.import_tag + '{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}' ) html = template.render(Context({})) self.assertEqual(html, '')
def services(request): all_services = Service.objects.active().order_by('name') context = Context({'all_services': all_services, 'title': "Services"}) return render(request, "services/services_list.html", context)
def render(self, template, context): # Why on Earth does Django not have a TemplateTestCase yet? t = Template(template) c = Context(context) return t.render(c)
def test_node(self): r = HubSpotNode().render(Context()) assert ("n.id=i;n.src='//js.hs-analytics.net/analytics/'" "+(Math.ceil(new Date()/r)*r)+'/1234.js';") in r
def render_template(template_text, context_dict, action=None): """ Given a template text and a context, performs the rendering of the template using the django template mechanism but with an additional pre-processing to bypass the restriction imposed by Jinja/Django that the variable names must start with a letter followed by a letter, number or _. In OnTask, the variable names are: column names, attribute names, or condition names. It is too restrictive to propagate the restrictions imposed by Jinja variables all the way to these three components. To hide this from the users, there is a preliminary step in which those variables in the template and keys in the context that do not comply with the syntax restriction are renamed to compliant names. The problem: We are giving two objects: a string containing a template with two markup structures denoting the use of variables, and a dictionary that matches variables to values. The processing of the template is done through Django template engine (itself based in Jinja). The syntax for the variables appearing in the template is highly restrictive. It only allows names starting with a letter followed by letter, number or '_'. No other printable symbol is allowed. We want to relax this last restriction. The solution: 1) Parse the template and detect the use of all variables. 2) For each variable use, transform its name into a name that is legal for Jinja (starts with letter followed by letter, number or '_' *) The transformation is based on: - Every non-letter or number is replaced by '_' followed by a letter/number as specified by the dictionary below. - If the original variable does not start by a letter, insert a prefix. 3) Apply the same transformation for the keys in the given dictionary 4) Execute the new template with the new dictionary and return the result. :param template_text: Text in the template to be rendered :param context_dict: Dictionary used by Jinja to evaluate the template :param action: Action object to insert in the context in case it is needed by any other custom template. :return: The rendered template """ # Regular expressions detecting the use of a variable, or the # presence of a "{% MACRONAME variable %} construct in a string (template) var_use_res = [ re.compile('(?P<mup_pre>{{\s+)(?P<vname>.+?)(?P<mup_post>\s+\}\})'), re.compile('(?P<mup_pre>{%\s+if\s+)(?P<vname>.+?)(?P<mup_post>\s+%\})') ] # Steps 1 and 2. Apply the tranlation process to all variables that # appear in the the template text new_template_text = template_text for rexpr in var_use_res: new_template_text = rexpr.sub( lambda m: m.group('mup_pre') + \ translate(m.group('vname')) + \ m.group('mup_post'), new_template_text) new_template_text = '{% load vis_include %}' + new_template_text # Step 3. Apply the translation process to the context keys new_context = dict([(translate(escape(x)), y) for x, y in context_dict.items()]) # If the number of elements in the two dictionaries is different, we have # a case of collision in the translation. Need to stop immediately. assert len(context_dict) == len(new_context) if action_context_var in new_context: raise Exception('Name {0} is reserved.'.format(action_context_var)) new_context[action_context_var] = action if viz_number_context_var in new_context: raise Exception('Name {0} is reserved.'.format(viz_number_context_var)) new_context[viz_number_context_var] = 0 # Step 4. Return the redering of the new elements return Template(new_template_text).render(Context(new_context))
def body(self): ctx = Context(self.get_template_vars()) s = DjangoTemplate(self.alarm_class.body_template).render(ctx) return s
def edit(request): # Don't use request.amo_user since it has too much caching. amouser = UserProfile.objects.get(pk=request.user.id) if request.method == 'POST': # ModelForm alters the instance you pass in. We need to keep a copy # around in case we need to use it below (to email the user) original_email = amouser.email form = forms.UserEditForm(request.POST, request.FILES, request=request, instance=amouser) if form.is_valid(): messages.success(request, _('Profile Updated')) if amouser.email != original_email: # Temporarily block email changes. if settings.APP_PREVIEW: messages.error( request, 'Error', 'You cannot change your email on the ' 'developer preview site.') return jingo.render(request, 'users/edit.html', { 'form': form, 'amouser': amouser }) l = { 'user': amouser, 'mail1': original_email, 'mail2': amouser.email } log.info(u"User (%(user)s) has requested email change from " "(%(mail1)s) to (%(mail2)s)" % l) messages.info( request, _('Email Confirmation Sent'), _(u'An email has been sent to {0} to confirm your new ' 'email address. For the change to take effect, you ' 'need to click on the link provided in this email. ' 'Until then, you can keep logging in with your ' 'current email address.').format(amouser.email)) token, hash_ = EmailResetCode.create(amouser.id, amouser.email) url = '%s%s' % (settings.SITE_URL, reverse('users.emailchange', args=[amouser.id, token, hash_])) t = loader.get_template('users/email/emailchange.ltxt') c = {'domain': settings.DOMAIN, 'url': url} send_mail(_('Please confirm your email address ' 'change at %s' % settings.DOMAIN), t.render(Context(c)), None, [amouser.email], use_blacklist=False, real_email=True) # Reset the original email back. We aren't changing their # address until they confirm the new one amouser.email = original_email form.save() return redirect('users.edit') else: messages.error( request, _('Errors Found'), _('There were errors in the changes ' 'you made. Please correct them and ' 'resubmit.')) else: form = forms.UserEditForm(instance=amouser) return jingo.render(request, 'users/edit.html', { 'form': form, 'amouser': amouser, 'webapp': False })
def handle(self, *args, **options): output = [] time_now = timezone.now().strftime("%Y-%m-%d %H:%M") subject = getattr(settings, 'SUBSCRIBES_SUBJECT', _('«МК-Киев». Выбор редактора')) from_email_name = getattr(settings, 'SUBSCRIBES_FROM_EMAIL_NAME', 'no-reply') pretty_from_email_name = getattr(settings, 'SUBSCRIBES_PRETTY_FROM_EMAIL_NAME', 'МК-Киев') previous_day = timezone.now() - timedelta(days=1) try: articles = Article.objects.select_related().filter( activity=True, pub_date__gte=previous_day).order_by('-pub_date') except Article.DoesNotExist: raise CommandError('%s Articles does not exist' % time_now) # current_site = Site.objects.get_current() # domain = add_domain(current_site.domain, '', False) domain = "http://mkkiev.in.ua/" pretty_domain = domain.replace('http://', '').replace('https://', '').replace( '//', '').replace('www', '') # from_email = '%s <%s@%s>' % (pretty_from_email_name, from_email_name, pretty_domain) # print from_email # from_email = "*****@*****.**" from_email = "*****@*****.**" print from_email c = Context({ 'article_list': articles, 'subject': subject, 'domain': domain, 'pretty_domain': pretty_domain }) messages = [] for template_name in ('subscribes/email.txt', 'subscribes/email.html'): try: t = get_template(template_name) except TemplateDoesNotExist: raise CommandError('%s Template "%s" does not exist' % (template_name, time_now)) # unsubscribe link in %(unsubscribe_link)s messages.append(t.render(c)) try: # recipient_list = Subscribe.objects.filter(activity=True, site=settings.SITE_ID).values_list('email', flat=True).order_by('?') recipient_list = Subscribe.objects.filter( activity=True).values_list('email', flat=True).order_by('?') except Subscribe.DoesNotExist: raise CommandError('%s Subscribes does not exist' % time_now) def gen_emails(): for email in recipient_list: token = base64.encodestring( hmac.new(settings.SECRET_KEY, email, sha1).digest()).rstrip() unsubscribe_link = '%s%s?t=%s&e=%s&d=1' % ( domain, reverse('subscribes-index'), token, email) c = Context({'unsubscribe_link': unsubscribe_link}) t = Template(messages[0]) text_message = t.render(c) t = Template(messages[1]) html_message = t.render(c) msg = mail.EmailMultiAlternatives(subject, text_message, from_email, [email]) msg.attach_alternative(html_message, 'text/html') yield msg connection = mail.get_connection(fail_silently=True) try: connection.send_messages(gen_emails()) except SMTPException: raise output.append('%s Successfully sends mails to subscribes\n' % time_now) return '\n'.join(output)
def send_now(users, label, extra_context=None, on_site=True, *args, **kwargs): """ Creates a new notice. This is intended to be how other apps create new notices. notification.send(user, 'friends_invite_sent', { 'spam': 'eggs', 'foo': 'bar', ) You can pass in on_site=False to prevent the notice emitted from being displayed on the site. """ send = kwargs.get('send', False) if extra_context is None: extra_context = {} try: notice_type = NoticeType.objects.get(label=label) except (NoticeType.DoesNotExist, NoticeType.MultipleObjectsReturned): notice_type = None if notice_type: protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") current_site = Site.objects.get_current() notices_url = u"%s://%s%s" % ( protocol, unicode(current_site), reverse("notification_notices"), ) current_language = get_language() formats = ( 'full.html', 'short.txt', 'notice.html', ) # TODO make formats configurable for user in users: recipients = [] headers = {} # get user language for user from language store defined in # NOTIFICATION_LANGUAGE_MODULE setting try: language = get_notification_language(user) except LanguageStoreNotAvailable: language = None if language is not None: # activate the user's language activate(language) # test for request in the extra_context if 'request' in extra_context.keys(): context = RequestContext(extra_context['request']) extra_context.update({ "user": user, "notice": ugettext(notice_type.display), "notices_url": notices_url, "current_site": current_site, }) context.update(extra_context) else: # update context with user specific translations context = Context({ "user": user, "notice": ugettext(notice_type.display), "notices_url": notices_url, "current_site": current_site, }) context.update(extra_context) # get prerendered format messages messages = get_formatted_messages(formats, label, context) # Strip newlines from subject subject = ''.join( render_to_string('notification/email_subject.txt', { 'message': messages['short'][0], }, context).splitlines()) body = render_to_string('notification/email_body.txt', { 'message': messages['full'][0], }, context) Notice.objects.create(user=user, message=messages['notice'][0], notice_type=notice_type, on_site=on_site) if should_send(user, notice_type, "1", send=send) and user.email: # Email recipients.append(user.email) if messages['full'][1] == '.html': # headers = {'Content-Type': 'text/html'} content_type = 'html' else: # headers = {'Content-Type': 'text/plain'} content_type = 'text' email = EmailMessage(subject, body, settings.DEFAULT_FROM_EMAIL, recipients, headers=headers) email.content_subtype = content_type email.send() # reset environment to original language activate(current_language)
def render(self, context): linked_block = self.linked_block.resolve(context) template = select_template([linked_block.block.template_file, 'oscar/promotions/block_default.html']) args = dict(block=linked_block.block, **linked_block.block.template_context()) context = Context(args) return template.render(context)
def Promillekalkulator(request, promilleFOER, antallTIMER, vekt, kjoenn, alk_type, enhet_stoer, antall): # Alkoholinnhold i valgt drikkevare if alk_type == 'øl': volpros = 0.047 elif alk_type == 'hvitvin': volpros = 0.11 elif alk_type == 'rødvin': volpros = 0.13 elif alk_type == 'vodka': volpros = 0.40 elif alk_type == 'niseks': volpros == 0.96 else: FEIL_INPUT_ALKOHOLTYPE = '"%s" er ikke en gyldig drikkevare. Du er nødt til å velge en av drikkevarene ramset opp under innskrivingsfeltet. Gå tilbake og fyll inn på nytt.' % alk_type return HttpResponse(FEIL_INPUT_ALKOHOLTYPE) # Konstant for gutt/jente if kjoenn == 'babe': GJ_konst = 0.69 elif kjoenn == 'kar': GJ_konst = 0.805 else: FEIL_INPUT_KJOENN = 'Du skrev "%s" i feltet for kjønn. Du må skrive enten "babe" eller "kar".' % kjoenn return HttpResponse(FEIL_INPUT_KJOENN) # Alkoholinntak i gram Massetetthet_ETANOL = 791 Inntak = volpros * enhet_stoer * antall * Massetetthet_ETANOL # Promille Promille = Inntak / (vekt * GJ_konst) + promilleFOER - 0.15 * antallTIMER Promille = round(Promille, 2) if Promille < 0: Promille = 0 if Promille > 4: DAU = True else: DAU = False c = Context({ 'prom': promilleFOER, 'prom2': Promille, 'timer': antallTIMER, 'dodelig': DAU, 'kjoen': kjoenn, 'alk_type': alk_type, 'enhet_stoer': enhet_stoer, 'antall': antall }) return render(request, 'TEM_resultat_promille.html', c)
def action(request, app, cls, action_name, pk=None): try: _model = apps.get_model(app, cls) except LookupError as e: return page_not_found(request, e, 'error404.html') for group in loader.instance_actions[_model]: if action_name in loader.instance_actions[_model][group]: break form_action = loader.instance_actions[_model][group][action_name] action_verbose_name = form_action['verbose_name'] action_can_execute = form_action['can_execute'] action_condition = form_action['condition'] action_function = form_action['function'] action_message = 'message' in form_action and form_action['message'] or None action_permission = '{}.{}'.format(_model._meta.app_label, action_function.__name__) action_input = form_action['input'] action_display = form_action['display'] action_style = form_action['style'] action_redirect = form_action['redirect_to'] obj = pk and _model.objects.all( request.user).distinct().get(pk=pk) or _model() obj.request = request obj._user = request.user title = action_verbose_name redirect_to = None if check_condition(request.user, action_condition, obj) and (not action_can_execute or permissions.check_group_or_permission( request, action_permission)): f_return = None func = getattr(_model, action_function.__name__, action_function) form = factory.get_action_form(request, obj, form_action) if count_parameters_names(func) > 1 or action_input: if form.is_valid(): if 'instance' in form.fields: obj = form.cleaned_data['instance'] func = getattr(obj, action_function.__name__, action_function) params = [] for param in get_parameters_names(func, include_annotated=True): if param in form.cleaned_data: params.append(form.cleaned_data[param]) else: params.append( get_role_value_for_action(func, request.user, param)) try: f_return = func(*params) if not action_redirect: if count_parameters_names(func) > 0 or action_display: redirect_to = '..' else: redirect_to = '.' else: redirect_to = Template(action_redirect).render( Context({'self': obj})) except ValidationError as e: form.add_error(None, str(e.message)) else: try: if form.fields and form.is_valid() or not form.fields: if 'instance' in form.fields: obj = form.cleaned_data['instance'] func = getattr(obj, action_function.__name__, action_function) params = [] for param in get_parameters_names(func, include_annotated=True): params.append( get_role_value_for_action(func, request.user, param)) f_return = func(*params) if not action_redirect: if count_parameters_names(func) > 0 or action_display: redirect_to = '..' else: redirect_to = '.' else: redirect_to = Template(action_redirect).render( Context({'self': obj})) except ValidationError as e: if form.fields: form.add_error(None, str(e.message)) return httprr(request, '.', e.message, error=True) if f_return: template_name = '{}.html'.format(action_function.__name__) return return_response(f_return, request, title, action_style, template_name) elif redirect_to: return httprr(request, redirect_to, action_message) if form.title == _('Form'): form.title = action_verbose_name if form.submit_label == _('Send'): form.submit_label = action_verbose_name return render(request, 'default.html', locals()) else: return HttpResponseForbidden()
def test_english(self): result = self.TEMPLATE.render(Context({ 'request': Mock(LANGUAGE_CODE='en'), })) assert result.strip() == ''
def send_emails(emails, label, extra_context=None, on_site=True): """ This method accepts a list of email addresses as opposed to a list of users. This is a custom method as opposed to send(), send_now(), and queue() Just send the notice to a list of emails immediately. No new notice created here notification.send_emails(email_list, 'friends_invite_sent', { 'spam': 'eggs', 'foo': 'bar', ) """ if extra_context is None: extra_context = {} try: notice_type = NoticeType.objects.get(label=label) except: # Stop here because we need a notice_type return None headers = {} protocol = getattr(settings, "DEFAULT_HTTP_PROTOCOL", "http") current_site = Site.objects.get_current() notices_url = u"%s://%s%s" % ( protocol, unicode(current_site), reverse("notification_notices"), ) formats = ( 'full.html', 'short.txt', 'notice.html', ) # TODO make formats configurable # test for request in the extra_context if 'request' in extra_context.keys(): context = RequestContext(extra_context['request']) extra_context.update({ "notice": ugettext(notice_type.display), "notices_url": notices_url, "current_site": current_site, }) context.update(extra_context) else: # update context with user specific translations context = Context({ "notice": ugettext(notice_type.display), "notices_url": notices_url, "current_site": current_site, }) context.update(extra_context) # get prerendered format messages messages = get_formatted_messages(formats, label, context) if 'admin' in label: subject = messages['short'] body = messages['full'] else: subject = render_to_string('notification/email_subject.txt', {'message': mark_safe(messages['short'])}, context) body = render_to_string('notification/email_body.txt', {'message': mark_safe(messages['full'])}, context) if 'reply_to' in extra_context.keys(): reply_to = extra_context['reply_to'] headers['Reply-To'] = reply_to else: reply_to = '' sender = extra_context.get('sender', '') if not sender: sender = get_setting( 'site', 'global', 'siteemailnoreplyaddress') or settings.DEFAULT_FROM_EMAIL if not sender: sender = settings.DEFAULT_FROM_EMAIL sender_display = extra_context.get('sender_display', '') # Add quotes around display name to prevent errors on sending # when display name contains comma or other control characters, - jennyq from_display = '"%s"<%s>' % (sender_display, sender) if sender_display: headers['From'] = from_display recipient_bcc = extra_context.get('recipient_bcc') or [] content_type = 'html' # removing newlines subject = ''.join(subject.splitlines()) for email_addr in emails: recipients = [email_addr] if recipient_bcc: email = EmailMessage(subject, body, sender, recipients, recipient_bcc, headers=headers) else: email = EmailMessage(subject, body, sender, recipients, headers=headers) email.content_subtype = content_type try: email.send(fail_silently=True) # should we raise exception or not? except UnicodeError: pass to = ','.join(emails) bcc = ','.join(recipient_bcc) reply_to = reply_to or unicode() NoticeEmail.objects.create(emails=to, sender=sender, bcc=bcc, title=subject, content=body, reply_to=reply_to, from_display=from_display, notice_type=notice_type)
def inspect_container(request, id, template_name): res=json.loads(docker_api_get('/containers/%s/json' % id)) t = loader.get_template(template_name) c = Context({'inspect_data':res, 'request':request, 'active':"yes"}) return HttpResponse(t.render(c))
def test_no_lang(self): result = self.TEMPLATE.render(Context({ 'request': Mock(), })) assert result.strip() == ''
def test_textarea(self): rendered = self.template.render(Context({})) self.assertIn('ng-model="bai"', rendered) self.assertIn('hai', rendered)
def list_to_html_response(self, data, title='', header=None): html = Engine().from_string(HTML_TEMPLATE).render(Context(locals())) return HttpResponse(html)
def test_form_some_random_user_string_482(self): # Regression test for https://github.com/opal/issues/482 tpl = Template( '{% load forms %}{% icon "this-is-my-icon-shut-up-opal" %}') self.assertIn('<i class="this-is-my-icon-shut-up-opal"></i>', tpl.render(Context({})))
def images_list(request, template_name): res=json.loads(docker_api_get('/images/json')) t = loader.get_template(template_name) c = Context({'containers_list':res, 'request':request}) return HttpResponse(t.render(c))
def test_fa_icon(self): tpl = Template('{% load forms %}{% icon "fa-eye" %}') self.assertIn('<i class="fa fa-eye"></i>', tpl.render(Context({})))
def test_render(self): tpl = Template('{% load forms %}{% date_of_birth_field %}') rendered = tpl.render(Context({})) self.assertIn("editing.demographics.date_of_birth", rendered)
def test_static(self): tpl = Template('{% load forms %}{% static "DogOwner.name" %}') rendered = tpl.render(Context({})) self.assertIn('editing.dog_owner.name', rendered)
def test_glyph_icon(self): tpl = Template('{% load forms %}{% icon "glyphicon-boat" %}') self.assertIn('<i class="glyphicon glyphicon-boat"></i>', tpl.render(Context({})))
def test_change(self): tpl = Template( '{% load forms %}{% select label="hai" change="doStuff" model="bai" element_name="onions"%}' ) rendered = tpl.render(Context({})) self.assertIn('ng-change="doStuff"', rendered)
def test_date(self): tpl = Template( '{% load forms %}{% static "Demographics.date_of_birth" %}') rendered = tpl.render(Context({})) self.assertIn('editing.demographics.date_of_birth', rendered) self.assertIn('shortDate', rendered)