Python django.template.response.TemplateResponse() Examples

The following are 30 code examples of django.template.response.TemplateResponse(). 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.response , or try the search function .
Example #1
Source File: actions.py    From django-idcops with Apache License 2.0 7 votes vote down vote up
def movedown(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "下架"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = False
            obj.status = 'offline'
            obj.operator = request.user
            obj.units.all().update(actived=True, operator=obj.operator)
            obj.pdus.all().update(actived=True, operator=obj.operator)
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk, action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example #2
Source File: views.py    From handson-labs-2018 with MIT License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        form = self.get_form()
        hash_name = make_hashid()
        tar_file = self.make_tar_gz({
            f"{hash_name}.shp": form.files['shp'],
            f"{hash_name}.shx": form.files['shx'],
            f"{hash_name}.dbf": form.files['dbf'],
            f"{hash_name}.prj": form.files['prj'],
            f"{hash_name}.cpg": form.files['cpg'],
        })
        metadata = {
            "description": form.data['description'],
            "uploader": form.data['uploader'],
            "research_date": form.data['research_date']
        }
        key = f"shp/{hash_name}.tar.gz"
        context = self.get_context_data()
        if upload_file(key, tar_file.name, metadata=metadata):
            context['success'] = True
            return TemplateResponse(self.request, self.template_name, context=context)
        else:
            context['success'] = False
            return TemplateResponse(self.request, self.template_name, context=context) 
Example #3
Source File: actions.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def reclaim(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "回收"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = False
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example #4
Source File: actions.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def actived(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "停用"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = False
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag="停用",
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example #5
Source File: views.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def index(request, sitemaps,
          template_name='sitemap_index.xml', content_type='application/xml',
          sitemap_url_name='django.contrib.sitemaps.views.sitemap'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    sites = []
    for section, site in sitemaps.items():
        if callable(site):
            site = site()
        protocol = req_protocol if site.protocol is None else site.protocol
        sitemap_url = urlresolvers.reverse(
            sitemap_url_name, kwargs={'section': section})
        absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
        sites.append(absolute_url)
        for page in range(2, site.paginator.num_pages + 1):
            sites.append('%s?p=%s' % (absolute_url, page))

    return TemplateResponse(request, template_name, {'sitemaps': sites},
                            content_type=content_type) 
Example #6
Source File: actions.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def html_print(request, queryset):
    model = queryset.model
    opts = model._meta
    action = sys._getframe().f_code.co_name
    action_name = "打印"
    verify = queryset.values('status').order_by('status').distinct()
    if verify.count() > 1:
        mesg = "不允许打印多个不同状态的 {}".format(opts.verbose_name)
        return mesg
    extra_for = queryset.count() - 10 < 0
    if extra_for:
        extra_for = list(range(abs(queryset.count() - 10)))
    _extra = dict(
        extra_for=extra_for,
        ticket=int(time.time()),
    )
    context = construct_context(request, queryset, action, action_name)
    context.update(_extra)
    templates = ["%s/print.html" % (opts.model_name), "base/print.html"]
    return TemplateResponse(request, templates, context) 
Example #7
Source File: options.py    From bioforum with MIT License 6 votes vote down vote up
def render_delete_form(self, request, context):
        opts = self.model._meta
        app_label = opts.app_label

        request.current_app = self.admin_site.name
        context.update(
            to_field_var=TO_FIELD_VAR,
            is_popup_var=IS_POPUP_VAR,
            media=self.media,
        )

        return TemplateResponse(
            request,
            self.delete_confirmation_template or [
                "admin/{}/{}/delete_confirmation.html".format(app_label, opts.model_name),
                "admin/{}/delete_confirmation.html".format(app_label),
                "admin/delete_confirmation.html",
            ],
            context,
        ) 
Example #8
Source File: passwords.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        form = self.password_reset_form(request.POST)

        if form.is_valid():
            opts = {
                'use_https': request.is_secure(),
                'token_generator': self.password_reset_token_generator,
                'email_template_name': self.password_reset_email_template,
                'request': request,
                'domain_override': request.get_host()
            }

            if self.password_reset_from_email:
                opts['from_email'] = self.password_reset_from_email
            if self.password_reset_subject_template:
                opts['subject_template_name'] = self.password_reset_subject_template

            form.save(**opts)
            context = super(ResetPasswordSendView, self).get_context()
            return TemplateResponse(request, self.password_reset_done_template, context)
        else:
            return self.get(request, form=form) 
Example #9
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
def password_reset_done(request,
                        template_name='registration/password_reset_done.html',
                        extra_context=None):
    warnings.warn("The password_reset_done() view is superseded by the "
                  "class-based PasswordResetDoneView().",
                  RemovedInDjango21Warning, stacklevel=2)
    context = {
        'title': _('Password reset sent'),
    }
    if extra_context is not None:
        context.update(extra_context)

    return TemplateResponse(request, template_name, context)


# Doesn't need csrf_protect since no-one can guess the URL 
Example #10
Source File: views.py    From telemetry-analysis-service with Mozilla Public License 2.0 6 votes vote down vote up
def detail_zeppelin_job(request, id):
    """
    View to show the details for the scheduled Zeppelin job with the given ID.
    """
    spark_job = get_object_or_404(SparkJob, pk=id)
    response = ""
    if spark_job.results:
        markdown_url = "".join(
            [x for x in spark_job.results["data"] if x.endswith("md")]
        )
        bucket = settings.AWS_CONFIG["PUBLIC_DATA_BUCKET"]
        markdown_file = spark_job.provisioner.s3.get_object(
            Bucket=bucket, Key=markdown_url
        )
        response = markdown_file["Body"].read().decode("utf-8")

    context = {"markdown": response}
    return TemplateResponse(
        request, "atmo/jobs/zeppelin_notebook.html", context=context
    ) 
Example #11
Source File: actions.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def reactive(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "启用"
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = True
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example #12
Source File: views.py    From handson-labs-2018 with MIT License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        form = self.get_form()
        if not form.is_valid():
            context = self.get_context_data()
            context['sucess'] = False
            return TemplateResponse(self.request, self.template_name, context=context)
        hash_name = make_hashid()
        tar_file = self.make_tar_gz({
            "point.csv": form.files['point_csv'],
            "tree.csv": form.files['info_csv'],
        })
        metadata = {
            "description": form.data['description'],
            "uploader": form.data['uploader'],
            "research_date": form.data['research_date']
        }
        key = f"csv/{hash_name}.tar.gz"
        context = self.get_context_data()
        if upload_file(key, tar_file.name, metadata=metadata):
            context['success'] = True
            return TemplateResponse(self.request, self.template_name, context=context)
        else:
            context['success'] = False
            return TemplateResponse(self.request, self.template_name, context=context) 
Example #13
Source File: options.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def render_delete_form(self, request, context):
        opts = self.model._meta
        app_label = opts.app_label

        request.current_app = self.admin_site.name
        context.update(
            to_field_var=TO_FIELD_VAR,
            is_popup_var=IS_POPUP_VAR,
        )

        return TemplateResponse(request,
            self.delete_confirmation_template or [
                "admin/{}/{}/delete_confirmation.html".format(app_label, opts.model_name),
                "admin/{}/delete_confirmation.html".format(app_label),
                "admin/delete_confirmation.html"
            ], context) 
Example #14
Source File: sites.py    From bioforum with MIT License 6 votes vote down vote up
def app_index(self, request, app_label, extra_context=None):
        app_dict = self._build_app_dict(request, app_label)
        if not app_dict:
            raise Http404('The requested admin page does not exist.')
        # Sort the models alphabetically within each app.
        app_dict['models'].sort(key=lambda x: x['name'])
        app_name = apps.get_app_config(app_label).verbose_name
        context = dict(
            self.each_context(request),
            title=_('%(app)s administration') % {'app': app_name},
            app_list=[app_dict],
            app_label=app_label,
        )
        context.update(extra_context or {})

        request.current_app = self.name

        return TemplateResponse(request, self.app_index_template or [
            'admin/%s/app_index.html' % app_label,
            'admin/app_index.html'
        ], context)


# This global object represents the default admin site, for the common case.
# You can instantiate AdminSite in your own code to create a custom admin site. 
Example #15
Source File: views.py    From django-prometheus with Apache License 2.0 6 votes vote down vote up
def sql(request):
    databases = connections.databases.keys()
    query = request.GET.get("query")
    db = request.GET.get("database")
    if query and db:
        cursor = connections[db].cursor()
        cursor.execute(query, [])
        results = cursor.fetchall()
        return TemplateResponse(
            request,
            "sql.html",
            {"query": query, "rows": results, "databases": databases},
        )
    else:
        return TemplateResponse(
            request, "sql.html", {"query": None, "rows": None, "databases": databases}
        ) 
Example #16
Source File: actions.py    From django-idcops with Apache License 2.0 6 votes vote down vote up
def reoutbound(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "取消出库"
    queryset = queryset.filter(actived=False)
    if not queryset.exists():
        return "查无结果"

    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = True
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs)
            )
        return None

    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example #17
Source File: views.py    From django-sudo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dispatch(self, request):
        redirect_to = request.GET.get(REDIRECT_FIELD_NAME, REDIRECT_URL)

        # Make sure we're not redirecting to other sites
        if not is_safe_url(url=redirect_to, host=request.get_host()):
            redirect_to = resolve_url(REDIRECT_URL)

        if request.is_sudo():
            return HttpResponseRedirect(redirect_to)

        if request.method == "GET":
            request.session[REDIRECT_TO_FIELD_NAME] = redirect_to

        context = {
            "form": self.form_class(request.user, request.POST or None),
            "request": request,
            REDIRECT_FIELD_NAME: redirect_to,
        }
        if self.handle_sudo(request, redirect_to, context):
            return self.grant_sudo_privileges(request, redirect_to)
        if self.extra_context is not None:
            context.update(self.extra_context)
        return TemplateResponse(request, self.template_name, context) 
Example #18
Source File: views.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def password_reset_done(request,
                        template_name='registration/password_reset_done.html',
                        current_app=None, extra_context=None):
    context = {
        'title': _('Password reset sent'),
    }
    if extra_context is not None:
        context.update(extra_context)

    if current_app is not None:
        request.current_app = current_app

    return TemplateResponse(request, template_name, context)


# Doesn't need csrf_protect since no-one can guess the URL 
Example #19
Source File: sites.py    From bioforum with MIT License 6 votes vote down vote up
def index(self, request, extra_context=None):
        """
        Display the main admin index page, which lists all of the installed
        apps that have been registered in this site.
        """
        app_list = self.get_app_list(request)

        context = dict(
            self.each_context(request),
            title=self.index_title,
            app_list=app_list,
        )
        context.update(extra_context or {})

        request.current_app = self.name

        return TemplateResponse(request, self.index_template or 'admin/index.html', context) 
Example #20
Source File: views.py    From bioforum with MIT License 6 votes vote down vote up
def index(request, sitemaps,
          template_name='sitemap_index.xml', content_type='application/xml',
          sitemap_url_name='django.contrib.sitemaps.views.sitemap'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    sites = []  # all sections' sitemap URLs
    for section, site in sitemaps.items():
        # For each section label, add links of all pages of its sitemap
        # (usually generated by the `sitemap` view).
        if callable(site):
            site = site()
        protocol = req_protocol if site.protocol is None else site.protocol
        sitemap_url = reverse(sitemap_url_name, kwargs={'section': section})
        absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url)
        sites.append(absolute_url)
        # Add links to all pages of the sitemap.
        for page in range(2, site.paginator.num_pages + 1):
            sites.append('%s?p=%s' % (absolute_url, page))

    return TemplateResponse(request, template_name, {'sitemaps': sites},
                            content_type=content_type) 
Example #21
Source File: views.py    From django-users2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def registration_closed(request,
                        template_name='users/registration_closed.html',
                        current_app=None,
                        extra_context=None):
    context = {
        'title': _('Registration closed'),
    }
    if extra_context is not None:  # pragma: no cover
        context.update(extra_context)
    return TemplateResponse(request, template_name, context) 
Example #22
Source File: views.py    From django-sudo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_returns_template_response(self):
        self.login()
        self.request.is_sudo = lambda: False
        response = sudo(self.request)
        self.assertIsInstance(response, TemplateResponse)
        self.assertEqual(response.template_name, "sudo/sudo.html")  # default
        self.assertEqual(
            response.context_data[REDIRECT_FIELD_NAME], REDIRECT_URL
        )  # default
        form = response.context_data["form"]
        self.assertIsInstance(form, SudoForm)
        self.assertEqual(form.user, self.user) 
Example #23
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get(self, request, pk):
        return TemplateResponse(request, "fieldsight/site_survey_list.html", {'project':pk}) 
Example #24
Source File: views.py    From telemetry-analysis-service with Mozilla Public License 2.0 5 votes vote down vote up
def detail_spark_job(request, id):
    """
    View to show the details for the scheduled Spark job with the given ID.
    """
    spark_job = SparkJob.objects.get(pk=id)
    context = {"spark_job": spark_job}
    if spark_job.latest_run:
        context["modified_date"] = spark_job.latest_run.modified_at
    return TemplateResponse(request, "atmo/jobs/detail.html", context=context) 
Example #25
Source File: views.py    From telemetry-analysis-service with Mozilla Public License 2.0 5 votes vote down vote up
def detail_cluster(request, id):
    """View to show details about an existing cluster."""
    cluster = Cluster.objects.get(id=id)
    context = {
        "cluster": cluster,
        "modified_date": cluster.modified_at,
        "constance": constance,
    }
    return TemplateResponse(
        request=request, template="atmo/clusters/detail.html", context=context
    ) 
Example #26
Source File: views.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def newlawn(request, location):
    """This view creates a new Lawn instance in the database."""
    lawn = Lawn()
    lawn.location = location
    lawn.save()
    return TemplateResponse(request, "lawn.html", {"lawn": lawn}) 
Example #27
Source File: views.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def slow(request):
    """This view takes .1s to load, on purpose."""
    time.sleep(0.1)
    return TemplateResponse(request, "slow.html", {}) 
Example #28
Source File: views.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def help(request):
    # render does not instantiate a TemplateResponse, so it does not
    # increment the "by_templatename" counters.
    return render(request, "help.html", {}) 
Example #29
Source File: views.py    From django-prometheus with Apache License 2.0 5 votes vote down vote up
def index(request):
    return TemplateResponse(request, "index.html", {}) 
Example #30
Source File: views.py    From botbuilder-python with MIT License 5 votes vote down vote up
def templater(request, data):
    return TemplateResponse(request, "template.html", {"context": data})