python类Context()的实例源码

tasks.py 文件源码 项目:MetaCI 作者: SalesforceFoundation 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def send_notification_message(build_id, user_id):
    reset_database_connection()

    build = Build.objects.get(id=build_id)
    user = User.objects.get(id=user_id)

    try:
        log_lines = build.flows.order_by('-date_end')[0].log.split('\n')
    except:
        log_lines = build.log.split('\n')
    log_lines = '\n'.join(log_lines[-25:])

    template_txt = get_template('build/email.txt')
    template_html = get_template('build/email.html')

    context = {
        'build': build,
        'log_lines': log_lines,
    }

    subject = '[{}] Build #{} of {} {} - {}'.format(build.repo.name, build.id, build.branch.name, build.plan.name, build.get_status().upper())
    message = template_txt.render(Context(context))
    html_message = template_html.render(Context(context))

    return send_mail(subject, message, settings.FROM_EMAIL, [user.email], html_message=html_message)
signals.py 文件源码 项目:django-simplestore 作者: martinstastny 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def send_order_email_confirmation(sender, instance, **kwargs):
    """
    Send email to customer with order details.
    """
    order = instance
    message = get_template("emails/order_conf.html").render(Context({
        'order': order.get_serialized_data()
    }))
    mail = EmailMessage(
        subject="Order confirmation",
        body=message,
        from_email=EMAIL_ADMIN,
        to=[order.email],
        reply_to=[EMAIL_ADMIN],
    )
    mail.content_subtype = "html"
    return mail.send()
bootstrap4.py 文件源码 项目:django-bootstrap4 作者: zostera 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def bootstrap_formset_errors(*args, **kwargs):
    """
    Render formset errors

    **Tag name**::

        bootstrap_formset_errors

    **Parameters**:

        formset
            The formset that is being rendered

        layout
            Context value that is available in the template ``bootstrap4/form_errors.html`` as ``layout``.

    **Usage**::

        {% bootstrap_formset_errors formset %}

    **Example**::

        {% bootstrap_formset_errors formset layout='inline' %}
    """
    return render_formset_errors(*args, **kwargs)
ansible_api.py 文件源码 项目:geekcloud 作者: Mr-Linus 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def gen_sudo_script(role_list, sudo_list):
        # receive role_list = [role1, role2] sudo_list = [sudo1, sudo2]
        # return sudo_alias={'NETWORK': '/sbin/ifconfig, /ls'} sudo_user={'user1': ['NETWORK', 'SYSTEM']}
        sudo_alias = {}
        sudo_user = {}
        for sudo in sudo_list:
            sudo_alias[sudo.name] = sudo.commands

        for role in role_list:
            sudo_user[role.name] = ','.join(sudo_alias.keys())

        sudo_j2 = get_template('jperm/role_sudo.j2')
        sudo_content = sudo_j2.render(Context({"sudo_alias": sudo_alias, "sudo_user": sudo_user}))
        sudo_file = NamedTemporaryFile(delete=False)
        sudo_file.write(sudo_content)
        sudo_file.close()
        return sudo_file.name
views.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def search(request):
    if request.method == 'GET':
        search_text = request.GET.get('search_text')
        groupname = request.session.get('user_group')
        hasgroup = Group.objects.get(name=groupname)
        print search_text
        print hasgroup.name
        filelist = File.objects.filter(Q(name__icontains=search_text)&(Q(perm__groups=hasgroup)|Q(ispublic="True"))).distinct()
        # filelist = File.objects.filter((Q(name=search_text)|Q(ispublic="True"))).distinct()
        listoffiledir=list(filelist)
        folderlist = {}
        template = loader.get_template('wxWeb/index2.html')
        context = Context({
        'filepath': listoffiledir,
        'foldlist': folderlist,
        })
        return HttpResponse(template.render(context))
view.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def index(request):
    fileindexfolder = get_object_or_404(Folder, name="ab")
    # listoffiledir = [singlefile.file for singlefile in fileindexfolder.files ]
    hasuser = 'sclmmanager'
    listoffiledir = list(fileindexfolder.get_childfile_read())
    can_read_folder = list(fileindexfolder.get_childfolder_read())
#    can_read_folder = fileindexfolder.get_children()
    folderlist = []
    for id in can_read_folder:
        fold = Folder.objects.get(id=id)
    folderlist.append(fold)
    template = loader.get_template('wxWeb/index.html')
    context = Context({
        'filepath':listoffiledir,
    'foldlist': folderlist,
    })
    #print template.render(context)
    return HttpResponse(template.render(context))
defaults.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def bad_request(request, exception, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
defaults.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def permission_denied(request, exception, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    )
static.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c))
debug.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def default_urlconf(request):
    "Create an empty URLconf 404 error response."
    t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE)
    c = Context({
        "title": _("Welcome to Django"),
        "heading": _("It worked!"),
        "subheading": _("Congratulations on your first Django-powered page."),
        "instructions": _("Of course, you haven't actually done any work yet. "
            "Next, start your first app by running <code>python manage.py startapp [app_label]</code>."),
        "explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your "
            "Django settings file and you haven't configured any URLs. Get to work!"),
    })

    return HttpResponse(t.render(c), content_type='text/html')

#
# Templates are embedded in the file so that we know the error handler will
# always work even if the template loader is broken.
#
views.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def schedule_list_csv(request, slug=None):
    schedule = fetch_schedule(slug)

    presentations = Presentation.objects.filter(section=schedule.section)
    presentations = presentations.exclude(cancelled=True).order_by("id")

    response = HttpResponse(mimetype="text/csv")
    if slug:
        file_slug = slug
    else:
        file_slug = "presentations"
    response["Content-Disposition"] = 'attachment; filename="%s.csv"' % file_slug

    response.write(loader.get_template("schedule/schedule_list.csv").render(Context({
        "presentations": presentations,

    })))
    return response
widgets.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs=None):

        # Prepare values
        attrs = self.build_attrs(attrs, name=name)
        if not value:
            value = ''

        options = getattr(settings, 'MARKEDIT_DEFAULT_SETTINGS', {})

        if 'options' in attrs:
            options = self._eval_value(attrs['options'], {})
            del attrs['options']

        # Render widget to HTML
        t = loader.get_template('markedit/ui.html')
        c = Context({
            'attributes': self._render_attrs(attrs),
            'value': conditional_escape(force_unicode(value)),
            'id': attrs['id'],
            'options': options,
        })

        return t.render(c)
widgets.py 文件源码 项目:django-happenings 作者: natgeosociety 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def render(self, name, value, attrs=None):
        if attrs is None:
            attrs = {}
        # it's called "original" because it will be replaced by a copy
        attrs['class'] = 'hstore-original-textarea'

        # get default HTML from AdminTextareaWidget
        html = super(BaseAdminHStoreWidget, self).render(name, value, attrs)

        # prepare template context
        template_context = Context({
            'field_name': name,
            'STATIC_URL': settings.STATIC_URL,
            'use_svg': django.VERSION >= (1, 9),  # use svg icons if django >= 1.9
        })
        # get template object
        template = get_template('happenings/hstore_%s_widget.html' % self.admin_style)
        # render additional html
        additional_html = template.render(template_context)

        # append additional HTML and mark as safe
        html = html + additional_html
        html = mark_safe(html)

        return html
editable.py 文件源码 项目:blog_django 作者: chnpmy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c))
tests.py 文件源码 项目:django-echoices 作者: mbourqui 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_simple(self):
        tpl = Template("""
<div class="echoices">
{{ echoices }}
</div>
<div class="echoices.FIELD1">
{{ echoices.FIELD1 }}
</div>
<div class="echoices.FIELD1.value">
{{ echoices.FIELD1.value }}
</div>
<div class="echoices.FIELD1.label">
{{ echoices.FIELD1.label }}
</div>
""")
        ctx = Context(dict(echoices=ETestCharChoices))
        rendered = tpl.render(ctx)
        rendered = str(rendered.strip())
        self.assertIn(ETestCharChoices.FIELD1.name, rendered)
        self.assertIn(ETestCharChoices.FIELD1.value, rendered)
        self.assertIn(ETestCharChoices.FIELD1.label, rendered)
tests.py 文件源码 项目:django-echoices 作者: mbourqui 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_iteration(self):
        tpl = Template("""
{% for e in echoices %}
    <div class="e">
    {{ e }}
    </div>
    <div class="e.value">
    {{ e.value }}
    </div>
    <div class="e.label">
    {{ e.label }}
    </div>
{% endfor %}
""")
        ctx = Context(dict(echoices=ETestCharChoices))
        rendered = tpl.render(ctx)
        rendered = str(rendered.strip())
        for e in ETestCharChoices:
            self.assertIn(e.name, rendered)
            self.assertIn(e.value, rendered)
            self.assertIn(e.label, rendered)
django.py 文件源码 项目:django-render-block 作者: clokep 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
editable.py 文件源码 项目:dream_blog 作者: fanlion 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c))
base.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, basestring) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)

            _dict['autoescape'] = context.autoescape
            _dict['use_l10n'] = context.use_l10n
            _dict['use_tz'] = context.use_tz
            _dict['admin_view'] = context['admin_view']

            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                _dict['csrf_token'] = csrf_token
            nodes.append(t.render(_dict))

        return method
    return wrap
editable.py 文件源码 项目:MxOnline 作者: myTeemo 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c))
transition.py 文件源码 项目:django-lb-workflow 作者: vicalloy 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def raise_no_permission_exception(self, instance=None):
        from django.template import Context, Template
        t = Template("""
            <!DOCTYPE HTML>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title></title>
            </head>
            <body>
                No permission to perform this action
                {% if instance %}
                    <br/>
                    <a href="{% url 'wf_detail' instance.pk %}"> View this process </a>
                {% endif %}
            </body>
            </html>
            """)
        http_response = HttpResponse(
            t.render(Context({"instance": instance})), content_type='text/html', status=403)
        raise HttpResponseException(http_response)
admin.py 文件源码 项目:django-hijack-admin 作者: arteria 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def hijack_field(self, obj):
        hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES

        if 'user_id' in hijack_attributes:
            hijack_url = reverse('hijack:login_with_id', args=(obj.pk, ))
        elif 'email' in hijack_attributes:
            hijack_url = reverse('hijack:login_with_email', args=(obj.email, ))
        else:
            hijack_url = reverse('hijack:login_with_username', args=(obj.username, ))

        button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE)
        button_context = {
            'hijack_url': hijack_url,
            'username': str(obj),
        }
        if VERSION < (1, 8):
            button_context = Context(button_context)

        return button_template.render(button_context)
masscontact.py 文件源码 项目:cerberus-core 作者: ovh 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _send_mass_contact_email(ticket, email_subject, email_body):

    template = loader.get_template_from_string(email_subject)
    context = Context({
        'publicId': ticket.publicId,
        'service': ticket.service.name.replace('.', '[.]'),
        'lang': ticket.defendant.details.lang,
    })
    subject = template.render(context)

    template = loader.get_template_from_string(email_body)
    context = Context({
        'publicId': ticket.publicId,
        'service': ticket.service.name.replace('.', '[.]'),
        'lang': ticket.defendant.details.lang,
    })
    body = template.render(context)

    implementations.instance.get_singleton_of('MailerServiceBase').send_email(
        ticket,
        ticket.defendant.details.email,
        subject,
        body,
        'MassContact',
    )
editable.py 文件源码 项目:djangoblog 作者: liuhuipy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c))
helper.py 文件源码 项目:pyconapac-2016 作者: pythonkr 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def send_email_ticket_confirm(request, payment_info):
    """
    :param request Django request object
    :param payment_info Registration object
    """
    mail_title = u"PyCon APAC 2016 ???? ??(Registration confirmation)"
    product = Product()
    variables = Context({
        'request': request,
        'payment_info': payment_info,
        'amount': product.price
    })
    html = get_template('mail/ticket_registered_html.html').render(variables)
    text = get_template('mail/ticket_registered_text.html').render(variables)

    msg = EmailMultiAlternatives(
        mail_title,
        text,
        settings.EMAIL_SENDER,
        [payment_info.email])
    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False)
editable.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get(self, request, object_id):
        model_fields = [f.name for f in self.opts.fields]
        fields = [f for f in request.GET['fields'].split(',') if f in model_fields]
        defaults = {
            "form": self.form,
            "fields": fields,
            "formfield_callback": self.formfield_for_dbfield,
        }
        form_class = modelform_factory(self.model, **defaults)
        form = form_class(instance=self.org_obj)

        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        form.helper = helper

        s = '{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}' + \
            '<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>'
        t = template.Template(s)
        c = template.Context({'form': form, 'action_url': self.model_admin_url('patch', self.org_obj.pk)})

        return HttpResponse(t.render(c))
compat.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def template_render(template, context=None, request=None):
    """
    Passing Context or RequestContext to Template.render is deprecated in 1.9+,
    see https://github.com/django/django/pull/3883 and
    https://github.com/django/django/blob/1.9/django/template/backends/django.py#L82-L84

    :param template: Template instance
    :param context: dict
    :param request: Request instance
    :return: rendered template as SafeText instance
    """
    if isinstance(template, Template):
        if request:
            context = RequestContext(request, context)
        else:
            context = Context(context)
        return template.render(context)
    # backends template, e.g. django.template.backends.django.Template
    else:
        return template.render(context, request=request)
tasks.py 文件源码 项目:teamreporter 作者: agilentia 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def send_summary(report_pk):
    report = Report.objects.get(pk=report_pk)
    daily = report.get_daily()
    messages = []
    questions = daily.report.question_set.active()
    surveys = daily.survey_set.all()
    for user in report.stakeholders:
        context = Context({'user': user,
                           'daily': daily,
                           'surveys': surveys,
                           'questions': questions})
        context['SITE_URL'] = settings.SITE_URL
        subject = render_to_string('email/summary_subject.txt', context)

        text = get_template('email/summary.txt')
        html = get_template('email/summary.html')
        text_content = text.render(context)
        html_content = html.render(context)
        messages.append([subject, text_content, html_content, settings.DEFAULT_FROM_EMAIL, [user.email]])

    send_mass_html_mail(messages)
    daily.summary_submitted = now()
    daily.save()
test_templates.py 文件源码 项目:dd-trace-py 作者: DataDog 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_template(self):
        # prepare a base template using the default engine
        template = Template("Hello {{name}}!")
        ctx = Context({'name': 'Django'})

        # (trace) the template rendering
        start = time.time()
        eq_(template.render(ctx), 'Hello Django!')
        end = time.time()

        # tests
        spans = self.tracer.writer.pop()
        assert spans, spans
        eq_(len(spans), 1)

        span = spans[0]
        eq_(span.span_type, 'template')
        eq_(span.name, 'django.template')
        eq_(span.get_tag('django.template_name'), 'unknown')
        assert start < span.start < span.start + span.duration < end
test_templatetags.py 文件源码 项目:django-mpathy 作者: craigds 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_render_recursetree(db):
    a = MyTree.objects.create(label='a')
    MyTree.objects.create(label='ab', parent=a)

    t = Template(
        "{% load mpathy %}{% recursetree nodes %}"
        "{% for node in nodes %}\n"
        "    <li>{{ node.label }}<ul>{% recurse node.get_children %}</ul></li>"
        "{% endfor %}"
        "{% endrecursetree %}"
    )

    context = Context({
        'nodes': MyTree.objects.all(),
    })
    rendered = t.render(context)

    assert rendered == (
        '\n'
        '    <li>a<ul>\n'
        '    <li>ab<ul></ul></li></ul></li>'
    )


问题


面经


文章

微信
公众号

扫码关注公众号