コード例 #1
0
def upload(request):
    context = dict()
    if request.method == 'GET':
        context['csrf_token'] = csrf_token_lazy(request)
    if request.method == 'POST':
        if request.FILES.get('upload_image', None):
            Image.objects.create(image_field=request.FILES.get('upload_image'))
            return HttpResponseRedirect(reverse('main_page'))
        if request.POST.get('image_url', None):
            image_url = request.POST.get('image_url')
            try:
                response = requests.get(image_url)
                if response.status_code == 200 and check_content_type_by_response(
                        response.headers):
                    buf_file = BytesIO()
                    buf_file.write(response.content)
                    filename = image_url.split('/')[-1]
                    image_ex = Image()
                    image_ex.image_field.save(filename, ImageFile(buf_file))
                    image_ex.save()
                    return HttpResponseRedirect(reverse('main_page'))
                else:
                    context['warning'] = 'this URL does not contain a image'
            except requests.ConnectionError:
                context['warning'] = 'Connection refused, use other url'
    return render(request, 'upload_page.html', context=context)
コード例 #2
0
ファイル: backends.py プロジェクト: Jianchun1/zulip
        def render(self, context=None, request=None):
            # type: (Optional[Union[Dict[str, Any], Context]], Optional[HttpRequest]) -> text_type
            if context is None:
                context = {}

            if isinstance(context, Context):
                # Jinja2 expects a dictionary
                # This condition makes sure that `flatten` is called only when
                # `context` is an instance of `Context`.
                #
                # Note: If we don't ignore then mypy complains about missing
                # `flatten` attribute in some members of union.
                context = context.flatten()  # type: ignore

            if request is not None:
                context['request'] = request
                context['csrf_input'] = csrf_input_lazy(request)
                context['csrf_token'] = csrf_token_lazy(request)

                for context_processor in self.context_processors:
                    cp = import_string(context_processor)
                    context.update(cp(request))

            if self.debug:
                template_rendered.send(sender=self, template=self,
                                       context=context)

            return self.template.render(context)
コード例 #3
0
ファイル: backends.py プロジェクト: cloudera/hue
    def render(self, context=None, request=None):
        """
        Render the template with a given context. Here we're adding
        some context variables that are required for all templates in
        the system like the statix url and the CSRF tokens, etc.

        :param context: It must be a dict if provided
        :param request: It must be a django.http.HttpRequest if provided
        :return: A rendered template
        """
        if context is None:
            context = {}

        if request is not None:
            # As Django doesn't have a global request object,
            # it's useful to put it in the context.
            context['request'] = request
            # Passing the CSRF token is mandatory.
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

            context['static'] = static
            context['url'] = reverse

        return self.template.render(**context)
コード例 #4
0
    def render(self, context=None, request=None):
        # type: (Optional[Union[Dict[str, Any], Context]], Optional[HttpRequest]) -> Text
        if context is None:
            context = {}

        if isinstance(context, Context):
            # Jinja2 expects a dictionary
            # This condition makes sure that `flatten` is called only when
            # `context` is an instance of `Context`.
            #
            # Note: If we don't ignore then mypy complains about missing
            # `flatten` attribute in some members of union.
            context = context.flatten()  # type: ignore

        if request is not None:
            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

            for context_processor in self.context_processors:
                cp = import_string(context_processor)
                context.update(cp(request))

        if self.debug:
            template_rendered.send(sender=self, template=self, context=context)

        return self.template.render(context)
コード例 #5
0
ファイル: views.py プロジェクト: JiHab/openweathermap
def home(request):

    if request.GET:
        city_name = request.GET.get('cityName', '')
        weather_d = backend.save_city_weather(city_name)
    else:
        weather_d = backend.save_city_weather()

    weather = weather_d['last_weather']
    weather_set = weather_d['forecast_pressure_dict']
    temperature = weather_d['list_temp']

    template_gc = loader.get_template("g_charts.html")

    context = {
        'values': weather_set,
        'weather': weather,
        'temp': temperature,
        'csrf_input': csrf_input_lazy(request),
        'csrf_token': csrf_token_lazy(request),
        'city': 'in ' + city_name
    }

    # return HttpResponse(template.render(context))
    return HttpResponse(template_gc.render(context))
コード例 #6
0
    def render(self, context=None, request=None):
        """
        Render the template with a given context. Here we're adding
        some context variables that are required for all templates in
        the system like the statix url and the CSRF tokens, etc.

        :param context: It must be a dict if provided
        :param request: It must be a django.http.HttpRequest if provided
        :return: A rendered template
        """
        if context is None:
            context = {}

        if request is not None:
            # As Django doesn't have a global request object,
            # it's useful to put it in the context.
            context['request'] = request
            # Passing the CSRF token is mandatory.
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

            context['static'] = static
            context['url'] = reverse

        return self.template.render(**context)
コード例 #7
0
ファイル: django.py プロジェクト: webpages/templates
 def render(self, context=None, request=None):
     if context is None:
         context = {}
     if request is not None:
         context['request'] = request
         context['csrf_input'] = csrf_input_lazy(request)
         context['csrf_token'] = csrf_token_lazy(request)
     return self.template.render(context)
コード例 #8
0
 def render(self, context=None, request=None):
     if context is None:
         context = {}
     if request is not None:
         context['request'] = request
         context['csrf_input'] = csrf_input_lazy(request)
         context['csrf_token'] = csrf_token_lazy(request)
     return self.template.render(context)
コード例 #9
0
 def render(self, context=None, request=None):
     if context is None:
         context = {}
     if request is not None:
         context['request'] = request
         context['csrf_input'] = csrf_input_lazy(request)
         context['csrf_token'] = csrf_token_lazy(request)
     template = self.templateClass(searchList=[context])
     return template.respond()
コード例 #10
0
ファイル: jinja2utils.py プロジェクト: olivmaurel/termsearch
def stream_http_with_jinja2_template(request, template, context):

    j2_env = environment_with_loader()

    if request is not None:
        context['csrf_input'] = csrf_input_lazy(request)
        context['csrf_token'] = csrf_token_lazy(request)

    return StreamingHttpResponse(j2_env.get_template(template).generate(context))
コード例 #11
0
    def render(self, context=None, request=None):
        """
        Render the template with a given context. Here we're adding
        some context variables that are required for all templates in
        the system like the statix url and the CSRF tokens, etc.

        :param context: It must be a dict if provided
        :param request: It must be a django.http.HttpRequest if provided
        :return: A rendered template
        """
        if context is None:
            context = {}

        context['static'] = static
        context['url'] = self.get_reverse_url()

        if request is not None:
            # As Django doesn't have a global request object,
            # it's useful to put it in the context.
            context['request'] = request
            # Passing the CSRF token is mandatory.
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

        try:
            return self.template.render(**context)
        except Exception as e:
            traceback = RichTraceback()

            source = traceback.source
            if not source:
                # There's no template source lines then raise
                raise e

            source = source.split('\n')
            line = traceback.lineno
            top = max(0, line - 4)
            bottom = min(len(source), line + 5)
            source_lines = [(i + 1, source[i]) for i in range(top, bottom)]

            e.template_debug = {
                'name': traceback.records[5][4],
                'message': '{}: {}'.format(traceback.errorname,
                                           traceback.message),
                'source_lines': source_lines,
                'line': line,
                'during': source_lines[line - top - 1][1],
                'total': bottom - top,
                'bottom': bottom,
                'top': top + 1,
                # mako's RichTraceback doesn't return column number
                'before': '',
                'after': '',
            }

            raise e
コード例 #12
0
 def render(self, context=None, request=None):
     if context is None:
         context = {}
     if request is not None:
         context['request'] = request
         context['csrf_input'] = csrf_input_lazy(request)
         context['csrf_token'] = csrf_token_lazy(request)
         for cp in self.context_processors:
             context.update(cp(request))
     return self.template.render(context)
コード例 #13
0
ファイル: dj.py プロジェクト: sesh/knights-templater
 def render(self, context=None, request=None):
     if context is None:
         context = {}
     if request is not None:
         context['user'] = request.user
         context['request'] = request
         context['csrf_input'] = csrf_input_lazy(request)
         context['csrf_token'] = csrf_token_lazy(request)
     ctx = defaultdict(str)
     ctx.update(context)
     return self.template(ctx)
コード例 #14
0
ファイル: jinja2.py プロジェクト: neurobin/djpub
 def render(self, context=None, request=None):
     from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
     if context is None:
         context = {}
     if request is not None:
         context['request'] = request
         context['csrf_input'] = csrf_input_lazy(request)
         context['csrf_token'] = csrf_token_lazy(request)
         for context_processor in self.backend.template_context_processors:
             context.update(context_processor(request))
     return self.template.render(context)
コード例 #15
0
ファイル: tests.py プロジェクト: qinxij/superlist
    def test_home_page_returns_correct_html(self):

        request = HttpRequest()
        response = home_page(request)

        expected_html = render_to_string(
            'home.html',
            {
                'csrf_token': csrf_token_lazy(request),
            })
        self.assertEqual(response.content.decode(), expected_html)
コード例 #16
0
ファイル: backends.py プロジェクト: hsfzxjy/wisecitymbc3.0
 def render(self, context=None, request=None):
     if context is None:
         context = {}
     if request is not None:
         context['request'] = request
         lazy_csrf_input = csrf_input_lazy(request)
         context['csrf'] = lambda: lazy_csrf_input
         context['csrf_input'] = lazy_csrf_input
         context['csrf_token'] = csrf_token_lazy(request)
         for cp in self.context_processors:
             context.update(cp(request))
     return self.template.render(context)
コード例 #17
0
ファイル: engines.py プロジェクト: tony/django-docutils
    def render(self, context=None, request=None):
        context = self.options
        if request is not None:
            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)
        context = {
            'source': self.source,
            'writer_name': 'html'
        }

        return core.publish_parts(**context)['html_body']
コード例 #18
0
ファイル: backend.py プロジェクト: sbutler/django-jinja
    def render(self, context=None, request=None):
        if context is None:
            context = {}

        if request is not None:
            context["request"] = request
            context["csrf_input"] = csrf_input_lazy(request)
            context["csrf_token"] = csrf_token_lazy(request)

            # Support for django context processors
            for processor in self.backend.context_processors:
                context.update(processor(request))

        return self.template.render(context)
コード例 #19
0
ファイル: views.py プロジェクト: Purple666/fxjournal
def binary(request):
    if request.method == "POST":
        serializer = BinarySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            csrf_token = csrf_token_lazy(request)
            context = Context(
                {"entry": serializer.data, "csrf_token": csrf_token})
            template = binary_template.render(context=context)
            print(serializer.data)
            s = dict(serializer.data)
            s.update({"template": template})
            return Response(data=s)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
コード例 #20
0
ファイル: backend.py プロジェクト: akx/django-jinja
    def render(self, context=None, request=None):
        if context is None:
            context = {}

        if request is not None:
            context["request"] = request
            context["csrf_input"] = csrf_input_lazy(request)
            context["csrf_token"] = csrf_token_lazy(request)

            # Support for django context processors
            for processor in self.backend.context_processors:
                context.update(processor(request))

        return self.template.render(context)
コード例 #21
0
def csrf(request):
    '''
    Adds the "csrf_input" and "csrf_token" variables to the request.

    Following Django's lead, this processor is included in DMP's
    default context processors list. It does not need to be listed
    in settings.py.

    To include the <input name="csrf".../> control in your forms,
    use ${ csrf_input }.
    '''
    return {
        'csrf_input': csrf_input_lazy(request),
        'csrf_token': csrf_token_lazy(request),
    }
コード例 #22
0
 def render(self, context=None, request=None):
     genshi_context = GenshiContext()
     genshi_context['static'] = staticfiles_storage.url
     genshi_context['url'] = reverse
     if request is not None:
         genshi_context['request'] = request
         genshi_context['csrf_input'] = csrf_input_lazy(request)
         genshi_context['csrf_token'] = csrf_token_lazy(request)
     if context is not None:
         genshi_context.push(context)
     stream = self.template.generate(genshi_context)
     template_render.send(self, genshi_context=genshi_context)
     # this might raise a genshi.template.eval.UndefinedError (derived from
     # genshi.template.base.TemplateRuntimeError)
     return stream.render(self.serialization, doctype=self.doctype)
コード例 #23
0
    def render(self, context=None, request=None):
        base_url = self.get_base_url(request)
        if context is None:
            context = {}
        if request is not None:
            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

        html = weasyprint.HTML(
            string=self.template.render(make_context(context)),
            base_url=base_url,
        )
        html.render()
        return html.write_pdf()
コード例 #24
0
def csrf(request):
    '''
    Adds the "csrf_input" and "csrf_token" variables to the request.

    Following Django's lead, this processor is included in DMP's
    default context processors list. It does not need to be listed
    in settings.py.

    To include the <input name="csrf".../> control in your forms,
    use ${ csrf_input }.
    '''
    return {
        'csrf_input': csrf_input_lazy(request),
        'csrf_token': csrf_token_lazy(request),
    }
コード例 #25
0
ファイル: mako.py プロジェクト: rjusher/ez-django-mako
    def render(self, context=None, request=None):

        context_env = getattr(self, "env", {})

        if context is None:
            context = {}

        context.update(context_env)

        if request is not None:
            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

        return self.template.render(**context)
コード例 #26
0
ファイル: mako.py プロジェクト: xiejian0182/awifi_test
    def render(self, context=None, request=None):
        if context is None:
            context = {}

        if request is not None:
            for processor in self.context_processors:
                try:
                    context.update(processor(request))
                except Exception:  # pylint: disable=broad-except
                    pass

            context["request"] = request
            context["csrf_input"] = csrf_input_lazy(request)
            context["csrf_token"] = csrf_token_lazy(request)

        return self.template.render_unicode(**context)
コード例 #27
0
ファイル: mako.py プロジェクト: zhoubinbinya/bk-sops
    def render(self, context=None, request=None):
        if context is None:
            context = {}

        if request is not None:
            for processor in self.context_processors:
                try:
                    context.update(processor(request))
                except Exception:
                    pass

            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

        return self.template.render_unicode(**context)
コード例 #28
0
ファイル: backends.py プロジェクト: 8trust/zulip
        def render(self, context=None, request=None):
            if context is None:
                context = {}

            if isinstance(context, Context):
                context = context.flatten()  # Jinja2 expects a dictionary

            if request is not None:
                context['request'] = request
                context['csrf_input'] = csrf_input_lazy(request)
                context['csrf_token'] = csrf_token_lazy(request)

                for context_processor in self.context_processors:
                    cp = import_string(context_processor)
                    context.update(cp(request))

            return self.template.render(context)
コード例 #29
0
ファイル: backends.py プロジェクト: anujsrc/zulip
    def render(self, context=None, request=None):
        if context is None:
            context = {}

        if isinstance(context, Context):
            context = context.flatten()  # Jinja2 expects a dictionary

        if request is not None:
            context['request'] = request
            context['csrf_input'] = csrf_input_lazy(request)
            context['csrf_token'] = csrf_token_lazy(request)

            for context_processor in self.context_processors:
                cp = import_string(context_processor)
                context.update(cp(request))

        return self.template.render(context)
コード例 #30
0
ファイル: jinja2.py プロジェクト: Tiendil/dext
    def render(self, context=None, request=None):
        real_context = {}

        real_context["settings"] = project_settings

        if request is not None:
            real_context["request"] = request
            real_context["csrf_input"] = csrf_input_lazy(request)
            real_context["csrf_token"] = csrf_token_lazy(request)

            if self.engine:
                for processor in self.engine.template_context_processors:
                    real_context.update(processor(request))

        if context:
            real_context.update(context)

        return self.template.render(real_context)
コード例 #31
0
    def render(self, context=None, request=None):
        """ Rendre le template """
        output_context = context or dict()
        output_context.update(MakoTemplates.base_template_context)

        if request is not None:
            for processor in self.context_processors:
                # noinspection PyBroadException
                try:
                    output_context.update(processor(request))
                except Exception:
                    pass

        if request is not None:
            output_context['request'] = request
            output_context['csrf_input'] = csrf_input_lazy(request)
            output_context['csrf_token'] = csrf_token_lazy(request)

        return mark_safe(self.template.render(**output_context))
コード例 #32
0
ファイル: liquid.py プロジェクト: jg-rp/django-liquid
    def render(self, context=None, request=None):
        from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy

        if context is None:
            context = {}

        if request is not None:
            context["request"] = request
            context["csrf_input"] = csrf_input_lazy(request)
            context["csrf_token"] = csrf_token_lazy(request)
            for context_processor in self.backend.template_context_processors:
                context.update(context_processor(request))

        try:
            return self.template.render(context)
        except liquid.exceptions.LiquidSyntaxError as exc:
            new = TemplateSyntaxError(exc.args)
            new.template_debug = get_exception_info(exc)
            raise new from exc
コード例 #33
0
ファイル: views.py プロジェクト: Purple666/fxjournal
def stamp(request, id=None):
    if request.method == "POST":
        stamp = StampSerializer(data=request.data)

        if stamp.is_valid():
            stamp.save()
            csrf_token = csrf_token_lazy(request)
            date = parse_date(stamp.data["date"]).strftime('%B %d, %Y')
            context = Context(
                {"stamp": stamp.data, "csrf_token": csrf_token, 'date': date})
            template = stamp_template.render(context=context)
            s = dict(stamp.data)
            s.update({"template": template})
            return Response(data=s)
        return Response(stamp.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == "DELETE":
        try:
            stamp = TimeStamp.objects.get(id=id)
            stamp.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except TimeStamp.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
コード例 #34
0
ファイル: jinjafunc.py プロジェクト: dlangille/pgeu-system
def render_jinja_conference_response(request, conference, pagemagic,
                                     templatename, dictionary):
    # If ?test=1 is specified, try to load a template with .test in the
    # name.
    if request.GET.get('test', None) == '1':
        templatename = templatename + '.test'

    d = {
        'pagemagic': pagemagic,
        'csrf_input': csrf_input_lazy(request),
        'csrf_token': csrf_token_lazy(request),
        'messages': get_messages(request),
    }

    if request.user and request.user.is_authenticated():
        d.update({
            'username':
            request.user.username,
            'userfullname':
            '{0} {1}'.format(request.user.first_name, request.user.last_name),
            'useremail':
            request.user.email,
        })
    else:
        d.update({
            'username': None,
            'userfullname': None,
            'useremail': None,
        })
    if dictionary:
        d.update(dictionary)

    return HttpResponse(
        render_jinja_conference_template(conference, templatename, d),
        content_type='text/html',
    )