def test_render_table_templatetag_invalid_type(): template = Template('{% load django_tables2 %}{% render_table table %}') with pytest.raises(ValueError): template.render(Context({'request': build_request(), 'table': dict()}))
def test_adds_query_parameters_when_there_are_none(self): request = RequestFake('') template = Template("{% load add_query_parameter %}{% add_query_parameter request 'parameter' 'value' %}") self.assertEqual( template.render(Context({'request': request})), 'parameter=value')
def test_overwrites_query_parameters_if_they_exist(self): request = RequestFake('parameter=value') template = Template("{% load add_query_parameter %}{% add_query_parameter request 'parameter' 'bar' %}") self.assertEqual( template.render(Context({'request': request})), 'parameter=bar')
def test_template_shown_as_used(self): template = Template( "{% load component_tags %}{% component 'test_component' %}", name='root') templates_used = self.templates_used_to_render(template) self.assertIn('slotted_template.html', templates_used)
def render(self, form, form_style, context): return Template(self.html).render(context)
def subject(self): if not self._subject: self._subject = Template(self.drip_base.subject_template).render( self.context) return self._subject
def parse_template(value): return mark_safe(Template(value).render(Context()))
def render_template(self, template, **kwargs): if isinstance(template, six.string_types): template = Template(template) return template.render(Context(kwargs)).strip()
def tag_test(self, template, context, output): t = Template('{% load notifications_tags %}'+template) c = Context(context) self.assertEqual(t.render(c), output)
def index(request): fp = open("polls/index.html") template = Template(fp.read()) fp.close() return HttpResponse(template.render(Context({})))
def render_template(content, **context_args): """Create a template with content ``content`` that first loads the ``django_charting`` library.""" template = Template("{% load django_charting %}" + content) return template.render(Context(context_args))
def no_template_used(request): template = Template("This is a string-based template") return HttpResponse(template.render(Context({})))
def setup_class(cls): cls.request = Mock() cls.template = Template(''' {% load custom_filters %} {{ test|method:"test_method" }} ''')
def get_tickets(request): raw_response = """ {% load staticfiles %} {% load core_filters %} {% load srs_urls %} <table class="table table-condensed"> <thead> <tr> <th></th> <th></th> <th>Requestor</th> <th>Status</th> <th>Summary</th> </tr> </thead> <tbody> {% for ticket in tickets %} <tr id="ticket_{{ ticket.ticket_id }}" class={{ ticket.display_class }}> <td> <a onclick="openModalFrame('Ticket Summary', '{% url 'core:ticket_summary' ticket_id=ticket.ticket_id %}');" style="cursor:pointer;"> <img src="{% static 'images/srs_view_button.gif' %}"> </a> </td> <td> <a href="{% srs_edit_url ticket.ticket_id %}" target="_blank"> <img src="{% static 'images/srs_edit_button.gif' %}"> </a> </td> <td>{{ ticket.requestor_full_name }}</td> <td>{{ ticket.status }}</td> <td>{{ ticket.summary|clean_srs_escapes }}</td> </tr> {% endfor %} </tbody> </table>""" now = datetime.today() tickets = [ticket for ticket in get_ticket_list(request.user) if ticket['assigned_person'].strip() != 'ResnetAPI'] for ticket in tickets: if ((not ticket['assigned_person'] or ticket['assigned_person'] == request.user.get_full_name()) and (ticket['status'] != 'Pending Information' or ticket['updater_is_technician'] == False or ticket['date_updated'] + timedelta(weeks=1) < datetime.today())): time_difference = (now - ticket['date_updated']).total_seconds() / 86400 # 24 hours if time_difference < 3: ticket['display_class'] = 'bg-success' ticket['sort_order'] = 1 elif time_difference < 7: ticket['display_class'] = 'bg-info' ticket['sort_order'] = 2 elif time_difference < 14: ticket['display_class'] = 'bg-warning' ticket['sort_order'] = 3 else: ticket['display_class'] = 'bg-danger' ticket['sort_order'] = 4 else: ticket['display_class'] = 'bg-muted' ticket['sort_order'] = 5 ticket['modal_id'] = 'ticket_' + str(ticket['ticket_id']) tickets.sort(key=itemgetter('sort_order')) template = Template(raw_response) context = RequestContext(request, {'tickets': tickets}) response_html = template.render(context) data = { 'inner-fragments': { '#tickets-response': response_html } } return Response(data)
def fmWebDh(conn, cur, mdcode): """spdl, spzl, barcode, spcode, spname, dhamount, indhamount, statusconvert(prostatus), propacketqty, maxminstock, curstock, saletotal, indhamount_max, indhamount_min, saleweek1, saleweek2,saleweek3, saleweek4, cuxiao, curalloc]""" usercode = mdcode userid = theFmWebSql.getUserInfo(usercode)["UserId"] #sqlstr = "select mdcode, mdname, prodl_id, prodl, prozl_id, prozl, spcode, spname, suggest, suggest, status, packetqty1, maxval, minval, curqty, total_qty, yqmaxlimit, yqminlimit, week1_qty, week2_qty, week3_qty, week4_qty, cuxiao_1, allocqty, normalprice, assortment, barcode from dhalldata where assortment is not null and status < '5' and suggest > 0 and shelf > '-1' and dhtag='T' and mdcode='"+mdcode+"'" sqlstr = "select mdcode, mdname, prodl_id, prodl, prozl_id, prozl, spcode, spname, suggest, suggest, status, packetqty1, maxval, minval, curqty, total_qty, yqmaxlimit, yqminlimit, week1_qty, week2_qty, week3_qty, week4_qty, cuxiao_1, allocqty, normalprice, assortment, barcode from dhalldata where assortment is not null and status < '5' and suggest > 0 and shelf > '-1' and dhtag='T' and mdcode='"+mdcode+"'" cur.execute(sqlstr) result=cur.fetchall() conn.commit() try: mdname = result[0][1] result1 = [ x for x in result if x[25] == 'youtu'] result2 = [ x for x in result if x[25] == 'wutu' and x[2] != '05'] result3 = [ x for x in result if x[25] == 'wutu' and x[2] == '05'] result1_a = [ [x[2]+'_'+x[3], x[4]+'_'+x[5], x[26], x[6], x[7], str(convert(x[8])), str(convert(x[9])), statusconvert(x[10]), str(convert(x[11])),str(convert(x[12]))+'__'+str(convert(x[13])), str(convert(x[14])), str(convert(x[15])), x[16].strip(), x[17].strip(), str(convert(x[18])), str(convert(x[19])), str(convert(x[20])), str(convert(x[21])), x[22], str(convert(x[23]))] for x in result1] result2_a = [ [x[2]+'_'+x[3], x[4]+'_'+x[5], x[26], x[6], x[7], str(convert(x[8])), str(convert(x[9])), statusconvert(x[10]), str(convert(x[11])),str(convert(x[12]))+'__'+str(convert(x[13])), str(convert(x[14])), str(convert(x[15])), x[16].strip(), x[17].strip(), str(convert(x[18])), str(convert(x[19])), str(convert(x[20])), str(convert(x[21])), x[22], str(convert(x[23]))] for x in result2] result3_a =[ [x[2]+'_'+x[3], x[4]+'_'+x[5], x[26], x[6], x[7], str(convert(x[8])), str(convert(x[9])), statusconvert(x[10]), str(convert(x[11])),str(convert(x[12]))+'__'+str(convert(x[13])), str(convert(x[14])), str(convert(x[15])), x[16].strip(), x[17].strip(), str(convert(x[18])), str(convert(x[19])), str(convert(x[20])), str(convert(x[21])), x[22], str(convert(x[23]))] for x in result3] result12 = result1+ result2 suggestlist = [x[8] for x in result12] totalsku = len(result1_a + result2_a) totalqty = reduce(lambda x, y: x+y, suggestlist) fp = open('d:/vcms/lib/py/mana1/templates/mana1/dh.html') t = Template(fp.read()) fp.close() html=t.render(Context({'userid': userid, 'result':result1_a, 'result2':result2_a, 'result3':result3_a, 'totalsku':totalsku, 'totalqty':str(totalqty), 'mdname':mdname})) except: html=u'系统不能生成订货值' return html
from django.core.mail import EmailMessage os.environ["DJANGO_SETTINGS_MODULE"] = 'mysite.settings' django.setup() from grading.models import Assignment, Enrollment if __name__ == '__main__': parser = argparse.ArgumentParser( description="Send assessments using email for specified assignment.") parser.add_argument('assignment_id') args = parser.parse_args() assignment = Assignment.objects.get(pk=args.assignment_id) mail_template = Template(assignment.mail_body) subject = assignment.mail_subject for report in assignment.report_set.filter(mail_is_sent=False): enrollment = Enrollment.objects.get(course=assignment.course, student=report.student) if enrollment.is_active: print("Sending mail to %s" % report.student) context = Context({'student': report.student}) body = mail_template.render(context) email = EmailMessage(subject=subject, body=body, to=[report.student.email], bcc=['*****@*****.**']) try: email.attach_file(report.report.path) except ValueError: print("Not including report for student %s" % report.student)
def getHTML(request): context = RequestContext(request, {}) template = Template( """ {% load i18n %} <table> <tr> <td style="vertical-align:top; padding: 15px"> <button type="submit" class="btn btn-primary" id="import" onclick="import_show('{% trans "Import a spreadsheet" %}',null,true,uploadspreadsheetajax)" value="{% trans "import"|capfirst %}">{% trans "import"|capfirst %}</button> </td> <td style="padding: 15px 15px 0 15px"> <p>{% trans "Import input data from a spreadsheet.</p><p>The spreadsheet must match the structure exported with the task above." %}</p> </td> </tr> </table> <script> var xhr = {abort: function () {}}; var uploadspreadsheetajax = { url: '{{request.prefix}}/execute/launch/importworkbook/', success: function (data) { var el = $('#uploadResponse'); el.html(data); if (el.attr('data-scrolled')!== "true") { el.scrollTop(el[0].scrollHeight - el.height()); } $('#cancelbutton').html("{% trans 'Close' %}"); $('#importbutton').hide(); $("#animatedcog").css('visibility','hidden'); $('#cancelimportbutton').hide(); if (document.queryCommandSupported('copy')) { $('#copytoclipboard').show(); } $("#grid").trigger("reloadGrid"); }, xhrFields: { onprogress: function (e) { var el = $('#uploadResponse'); el.html(e.currentTarget.response); if (el.attr('data-scrolled')!== "true") { el.attr('data-scrolled', el[0].scrollHeight - el.height()); el.scrollTop(el[0].scrollHeight - el.height()); } } }, error: function() { $('#cancelimportbutton').hide(); $('#copytoclipboard').show(); $("#animatedcog").css('visibility','hidden'); $("#uploadResponse").scrollTop($("#uploadResponse")[0].scrollHeight); } }; </script> """ ) return template.render(context) # A list of translation strings from the above translated = ( _("import"), _("Import a spreadsheet"), _( "Import input data from a spreadsheet.</p><p>The spreadsheet must match the structure exported with the task above." ), )
def test_adds_class(self): context = Context({'form': MyForm()}) template = Template( '{% load addcss %} {{form.title|addcss:"my custom classes"}}') content = template.render(context) self.assertIn('class="my custom classes"', content)
def test_ifinstalled(self, app, result): template = Template( "{% load mezzanine_tags %}" f"{{% ifinstalled {app} %}}CONTENT{{% endifinstalled %}}") html = template.render(Context({})) assert ("CONTENT" in html) == result
def test_should_make_a_menu_link_as_active(self): html = "{% load menu %}{% is_active request.get_full_path 'home' %}" template = Template(html) context = Context({'request': {"get_full_path": "/"}}) self.assertEqual("active", template.render(context))
def render(self, path): request = RequestFactory().get(path) request.flag_conditions = get_flags() template = Template("{% load hmda_banners %}" "{% hmda_outage_banner request %}") return template.render(Context({"request": request}))
def should_make_a_menu_link_as_not_active(self): html = "{% is_active request.get_full_path 'home' %}" template = Template(html) context = Context({'request': {"get_full_path": "register"}}) self.assertNotEqual("active", template.render(context))
def render(self, context): if self.is_variable: real_key = template.Variable(self.key).resolve(context) else: real_key = self.key if isinstance(self.template_name, template.Variable): real_tpl = self.template_name.resolve(context) else: real_tpl = self.template_name context['chunk_key'] = real_key if self.content_type == 'edit': context['tag'] = self.tag sources = dict(text=Chunk, edit=Chunk, image=Image, media=Media, group=Group) model = sources[self.content_type] obj = None # try to get cached object if self.cache_time > 0: cache_key = CACHE_PREFIX + self.content_type + get_language( ) + real_key obj = cache.get(cache_key) # otherwise get it from database if obj is None: if self.content_type == 'group': obj = model.objects.filter(key=real_key) else: try: obj = model.objects.get(key=real_key) except model.DoesNotExist: # this place we should create an empty object in database obj = model(key=real_key) if self.content_type == 'image': # image object must exist, so save the stub picture filename = join(dirname(__file__), '..', 'static', 'chunks', 'stub.png') with open(filename, 'r') as file: obj.image.save(basename(filename), File(file), save=True) else: obj.content = real_key obj.save() # cache the object if self.cache_time == 0: logger.debug("Don't cache %s" % (real_key, )) else: if self.cache_time is None or self.cache_time == 'None': logger.debug("Caching %s for the cache's default timeout" % real_key) cache.set(cache_key, obj) else: logger.debug("Caching %s for %s seconds" % (real_key, str(self.cache_time))) cache.set(cache_key, obj, int(self.cache_time)) # Eventually we want to pass the whole context to the template so that # users have the maximum of flexibility of what to do in there. if self.with_template: new_ctx = template.Context(context) if hasattr(obj, 'content'): obj.content = Template(obj.content).render(new_ctx) new_ctx.update({'obj': obj}) tpl = template.loader.get_template(real_tpl) return tpl.render(new_ctx) elif hasattr(obj, 'image'): return obj.image.url elif hasattr(obj, 'content'): return obj.content else: return None
def validate_template(self, value): try: Template(value) except TemplateSyntaxError as e: raise forms.ValidationError(six.text_type(e))
def _render_template(string, context=None): context = context or {} context = Context(context) return Template(string).render(context=context)
def test_strings_only(self): t = Template("""{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}""") self.assertEqual(t.render(Context({})).strip().split(), ['/vertaald/', '/traduzidos/'])
def test_adds_query_parameters_to_the_existing_ones(self): request = RequestFake('parameter=value') template = Template("{% load add_query_parameter %}{% add_query_parameter request 'foo' 'bar' %}") self.assertEqual( template.render(Context({'request': request})), 'foo=bar¶meter=value')
def test_kwargs(self): tpl = Template("""{% load i18n %} {% language 'nl' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %} {% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}""") self.assertEqual(tpl.render(Context({})).strip().split(), ['/vertaald/apo/', '/traduzidos/apo/'])
def test_gets_existing_key_from_dictionary(self): example_dict = {'foo': 'bar'} template = Template("{% load get_from_key %}{{ d|get_from_key:'foo' }}") self.assertEqual( template.render(Context({'d': example_dict})), 'bar')
def test_querystring_syntax_error(): with pytest.raises(TemplateSyntaxError): Template('{% load django_tables2 %}{% querystring foo= %}')