Python django.template.context.Context() Examples

The following are 14 code examples of django.template.context.Context(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.template.context , or try the search function .
Example #1
Source File: send_letter_email.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def send_letter_email(request, grad_slug, letter_slug):
    letter = get_object_or_404(Letter, slug=letter_slug)
    grad = get_object_or_404(GradStudent, person=letter.student.person, slug=grad_slug, program__unit__in=request.units)
    if request.method == 'POST':
        form = LetterEmailForm(request.POST)
        if form.is_valid():
            letter.set_email_body(form.cleaned_data['email_body'])
            letter.set_email_subject(form.cleaned_data['email_subject'])
            if 'email_cc' in form.cleaned_data:
                letter.set_email_cc(form.cleaned_data['email_cc'])
            letter.set_email_sent(timezone_today())
            letter.save()
            return _send_letter(request, grad_slug, letter)

    else:
        email_template = letter.template.email_body()
        temp = Template(email_template)
        ls = grad.letter_info()
        text = temp.render(Context(ls))
        form = LetterEmailForm(initial={'email_body': text, 'email_subject': letter.template.email_subject()})
    return render(request, 'grad/select_letter_email_text.html', {'form': form, 'grad': grad, 'letter': letter}) 
Example #2
Source File: admin_modify.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #3
Source File: route_view.py    From jet-bridge with MIT License 6 votes vote down vote up
def write_response(self, response):
        if isinstance(response, RedirectResponse):
            result = HttpResponseRedirect(response.url, status=response.status)
        elif isinstance(response, OptionalJSONResponse) and isinstance(response.data, HttpResponseBase):
            result = response.data
        elif isinstance(response, TemplateResponse):
            template_path = os.path.join(base_settings.BASE_DIR, 'templates', response.template)
            with open(template_path, 'r') as file:
                template = file.read()
                template = template.replace('{% end %}', '{% endif %}')
                context = Context(response.data)
                content = Template(template).render(context)
                result = HttpResponse(content, status=response.status)
        else:
            result = HttpResponse(response.render(), status=response.status)

        for name, value in self.view.default_headers().items():
            result[name] = value

        for name, value in response.header_items():
            result[name] = value

        return result 
Example #4
Source File: admin_modify.py    From python with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: admin_modify.py    From python2017 with MIT License 6 votes vote down vote up
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 
Example #6
Source File: views.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def get_memo_text(request, userid, event_slug, memo_template_id):
    """ Get the text from memo template """
    person, member_units = _get_faculty_or_404(request.units, userid)
    event = _get_event_or_404(units=request.units, slug=event_slug, person=person)
    lt = get_object_or_404(MemoTemplate, id=memo_template_id, unit__in=Unit.sub_units(request.units))
    temp = Template(lt.template_text)
    ls = event.memo_info()
    text = temp.render(Context(ls))

    return HttpResponse(text, content_type='text/plain') 
Example #7
Source File: get_letter_text.py    From coursys with GNU General Public License v3.0 5 votes vote down vote up
def get_letter_text(request, grad_slug, letter_template_id):
    """ Get the text from letter template """
    grad = get_object_or_404(GradStudent, slug=grad_slug, program__unit__in=request.units)
    lt = get_object_or_404(LetterTemplate, id=letter_template_id, unit__in=request.units)
    temp = Template(lt.content)
    ls = grad.letter_info()
    text = temp.render(Context(ls))
    #print ls

    return HttpResponse(text, content_type='text/plain') 
Example #8
Source File: django.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def render(self, context=None, request=None):
        # A deprecation path is required here to cover the following usage:
        # >>> from django.template import Context
        # >>> from django.template.loader import get_template
        # >>> template = get_template('hello.html')
        # >>> template.render(Context({'name': 'world'}))
        # In Django 1.7 get_template() returned a django.template.Template.
        # In Django 1.8 it returns a django.template.backends.django.Template.
        # In Django 1.10 the isinstance checks should be removed. If passing a
        # Context or a RequestContext works by accident, it won't be an issue
        # per se, but it won't be officially supported either.
        if isinstance(context, RequestContext):
            if request is not None and request is not context.request:
                raise ValueError(
                    "render() was called with a RequestContext and a request "
                    "argument which refer to different requests. Make sure "
                    "that the context argument is a dict or at least that "
                    "the two arguments refer to the same request.")
            warnings.warn(
                "render() must be called with a dict, not a RequestContext.",
                RemovedInDjango110Warning, stacklevel=2)

        elif isinstance(context, Context):
            warnings.warn(
                "render() must be called with a dict, not a Context.",
                RemovedInDjango110Warning, stacklevel=2)

        else:
            context = make_context(context, request)

        return self.template.render(context) 
Example #9
Source File: admin_modify.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 
Example #10
Source File: preview.py    From ontask_b with MIT License 5 votes vote down vote up
def _evaluate_row_action_in(action: models.Action, context: Mapping):
    """Evaluate an action_in in the given context.

    Given an action IN object and a row index:
    1) Create the form and the context
    2) Run the template with the context
    3) Return the resulting object (HTML?)

    :param action: Action object.
    :param context: Dictionary with pairs name/value
    :return: String with the HTML content resulting from the evaluation
    """
    # Get the active columns attached to the action
    tuples = [
        column_condition_pair
        for column_condition_pair in action.column_condition_pair.all()
        if column_condition_pair.column.is_active
    ]

    col_values = [context[colcon_pair.column.name] for colcon_pair in tuples]

    form = forms.EnterActionIn(
        None,
        tuples=tuples,
        context=context,
        values=col_values)

    # Render the form
    return Template(
        """<div align="center">
             <p class="lead">{{ description_text }}</p>
             {% load crispy_forms_tags %}{{ form|crispy }}
           </div>""",
    ).render(Context(
        {
            'form': form,
            'description_text': action.description_text,
        },
    )) 
Example #11
Source File: django.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def render(self, context=None, request=None):
        # A deprecation path is required here to cover the following usage:
        # >>> from django.template import Context
        # >>> from django.template.loader import get_template
        # >>> template = get_template('hello.html')
        # >>> template.render(Context({'name': 'world'}))
        # In Django 1.7 get_template() returned a django.template.Template.
        # In Django 1.8 it returns a django.template.backends.django.Template.
        # In Django 1.10 the isinstance checks should be removed. If passing a
        # Context or a RequestContext works by accident, it won't be an issue
        # per se, but it won't be officially supported either.
        if isinstance(context, RequestContext):
            if request is not None and request is not context.request:
                raise ValueError(
                    "render() was called with a RequestContext and a request "
                    "argument which refer to different requests. Make sure "
                    "that the context argument is a dict or at least that "
                    "the two arguments refer to the same request.")
            warnings.warn(
                "render() must be called with a dict, not a RequestContext.",
                RemovedInDjango110Warning, stacklevel=2)

        elif isinstance(context, Context):
            warnings.warn(
                "render() must be called with a dict, not a Context.",
                RemovedInDjango110Warning, stacklevel=2)

        else:
            context = make_context(context, request)

        try:
            return self.template.render(context)
        except TemplateDoesNotExist as exc:
            reraise(exc, self.backend) 
Example #12
Source File: request_history.py    From django-debug-toolbar-request-history with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def content(self):
        """ Content of the panel when it's displayed in full screen. """
        toolbars = OrderedDict()
        for id, toolbar in DebugToolbar._store.items():
            content = {}
            for panel in toolbar.panels:
                panel_id = None
                nav_title = ''
                nav_subtitle = ''
                try:
                    panel_id = panel.panel_id
                    nav_title = panel.nav_title
                    nav_subtitle = panel.nav_subtitle() if isinstance(
                        panel.nav_subtitle, Callable) else panel.nav_subtitle
                except Exception:
                    logger.debug('Error parsing panel info:', exc_info=True)
                if panel_id is not None:
                    content.update({
                        panel_id: {
                            'panel_id': panel_id,
                            'nav_title': nav_title,
                            'nav_subtitle': nav_subtitle,
                        }
                    })
            toolbars[id] = {
                'toolbar': toolbar,
                'content': content
            }
        return get_template().render(Context({
            'toolbars': OrderedDict(reversed(list(toolbars.items()))),
            'trunc_length': get_config().get('RH_POST_TRUNC_LENGTH', 0)
        })) 
Example #13
Source File: filters.py    From devops with MIT License 5 votes vote down vote up
def __str__(self):
        tpl = get_template(self.template)
        return mark_safe(tpl.render(Context(self.get_context()))) 
Example #14
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def add_service(request, username, id_string):
    data = {}
    form = RestServiceForm()
    xform = get_object_or_404(
        XForm, user__username__iexact=username, id_string__exact=id_string)
    if request.method == 'POST':
        form = RestServiceForm(request.POST)
        restservice = None
        if form.is_valid():
            service_name = form.cleaned_data['service_name']
            service_url = form.cleaned_data['service_url']
            try:
                rs = RestService(service_url=service_url,
                                 name=service_name, xform=xform)
                rs.save()
            except IntegrityError:
                message = _(u"Service already defined.")
                status = 'fail'
            else:
                status = 'success'
                message = (_(u"Successfully added service %(name)s.")
                           % {'name': service_name})
                service_tpl = render_to_string("service.html", {
                    "sv": rs, "username": xform.user.username,
                    "id_string": xform.id_string})
                restservice = service_tpl
        else:
            status = 'fail'
            message = _(u"Please fill in all required fields")

            if form.errors:
                for field in form:
                    message += Template(u"{{ field.errors }}")\
                        .render(Context({'field': field}))
        if request.is_ajax():
            response = {'status': status, 'message': message}
            if restservice:
                response["restservice"] = u"%s" % restservice

            return HttpResponse(json.dumps(response))

        data['status'] = status
        data['message'] = message

    data['list_services'] = RestService.objects.filter(xform=xform)
    data['form'] = form
    data['username'] = username
    data['id_string'] = id_string

    return render(request, "add-service.html", data)