我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.template.response.SimpleTemplateResponse()。
def done(self, form_list, **kwargs): """ This step only runs if all forms are valid. Simply emits a simple template that uses JS to redirect to the newly created object. """ form_two = list(form_list)[1] instance = form_two.save() url = self.get_success_url(instance) if not url: page = self.get_origin_page() if page: try: url = page.get_absolute_url(self.language_code) except NoReverseMatch: url = '/' else: url = '/' return SimpleTemplateResponse("cms/wizards/done.html", {"url": url})
def _process(request, get_response): with force_debug_cursor(), managed( db_record_stacks=getattr(settings, 'CAVALRY_DB_RECORD_STACKS', True), ) as data: data['start_time'] = get_time() response = get_response(request) if isinstance(response, SimpleTemplateResponse): response.render() data['end_time'] = get_time() data['duration'] = data['end_time'] - data['start_time'] data['databases'] = {} for conn in connections.all(): queries = conn.queries data['databases'][conn.alias] = { 'queries': queries, 'n_queries': len(queries), 'time': (sum(q.get('hrtime', 0) * 1000 for q in queries) if queries else 0), } inject_stats(request, response, data) post_stats_kwargs = {'request': request, 'response': response, 'data': data} if getattr(settings, 'CAVALRY_THREADED_POST', False): Thread(name='cavalry poster', target=post_stats, kwargs=post_stats_kwargs, daemon=False).start() else: post_stats(**post_stats_kwargs) return response
def response_delete(self, request, obj_display, obj_id): """ Determines the HttpResponse for the delete_view stage. """ opts = self.model._meta if IS_POPUP_VAR in request.POST: return SimpleTemplateResponse('admin/popup_response.html', { 'action': 'delete', 'value': escape(obj_id), }) self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % { 'name': force_text(opts.verbose_name), 'obj': force_text(obj_display), }, messages.SUCCESS) if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {'preserved_filters': preserved_filters, 'opts': opts}, post_url ) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url)
def response_delete(self, request, obj_display, obj_id): """ Determines the HttpResponse for the delete_view stage. """ opts = self.model._meta if IS_POPUP_VAR in request.POST: popup_response_data = json.dumps({ 'action': 'delete', 'value': str(obj_id), }) return SimpleTemplateResponse('admin/popup_response.html', { 'popup_response_data': popup_response_data, }) self.message_user( request, _('The %(name)s "%(obj)s" was deleted successfully.') % { 'name': force_text(opts.verbose_name), 'obj': force_text(obj_display), }, messages.SUCCESS, ) if self.has_change_permission(request, None): post_url = reverse( 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {'preserved_filters': preserved_filters, 'opts': opts}, post_url ) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url)
def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.list_queryset.query.where: self.full_result_count = self.result_count else: self.full_result_count = self.base_queryset.count() self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('xadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list))
def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('xadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list))
def get_error_response(error_message): return SimpleTemplateResponse( 'enrolment-error.html', {'validation_error': error_message}, )
def get(self, request, *args, **kwargs): """Add message and perform redirect to get rid of paypal GET parameters""" context = self.get_context_data(**kwargs) if 'result' not in context: raise PermissionDenied if context['result']: template = 'payment/success.txt' else: template = 'payment/failure.txt' message = SimpleTemplateResponse(template, context).rendered_content messages.info(request, message) return HttpResponseRedirect(reverse('account'))
def response_add(self, request, obj, post_url_continue=None): ''' This just modifies the normal ModelAdmin process in order to pass capacity and room options for the added Location along with the location's name and ID. ''' IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) popup_response_data = json.dumps({ 'value': six.text_type(value), 'obj': six.text_type(obj), # Add this extra data 'defaultCapacity': obj.defaultCapacity, 'roomOptions': json.dumps([{'id': x.id, 'name': x.name, 'defaultCapacity': x.defaultCapacity} for x in obj.room_set.all()]), }) # Return a modified template return SimpleTemplateResponse('core/admin/location_popup_response.html', { 'popup_response_data': popup_response_data, }) # Otherwise just use the standard ModelAdmin method return super(LocationAdmin,self).response_add(request, obj, post_url_continue)
def response_change(self, request, obj): ''' This just modifies the normal ModelAdmin process in order to pass capacity and room options for the modified Location along with the location's name and ID. ''' IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) attr = str(to_field) if to_field else obj._meta.pk.attname # Retrieve the `object_id` from the resolved pattern arguments. value = request.resolver_match.args[0] new_value = obj.serializable_value(attr) popup_response_data = json.dumps({ 'action': 'change', 'value': six.text_type(value), 'obj': six.text_type(obj), 'new_value': six.text_type(new_value), # Add this extra data 'defaultCapacity': obj.defaultCapacity, 'roomOptions': json.dumps([{'id': x.id, 'name': x.name, 'defaultCapacity': x.defaultCapacity} for x in obj.room_set.all()]), }) # Return a modified template return SimpleTemplateResponse('core/admin/location_popup_response.html', { 'popup_response_data': popup_response_data, }) return super(LocationAdmin,self).response_change(request, obj)
def make_result_list(self): u""" ????????? result_list """ # ?????????? queryset self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # ??????? self.result_count = self.paginator.count if self.can_show_all: self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone(count=self.result_count) else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: # ????, ????????????? if defs.ERROR_FLAG in self.request.GET.keys(): return SimpleTemplateResponse('xadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + defs.ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list))
def dispatch(self, request, *args, **kwargs): response = super(TwilioResponseMixin, self).dispatch(request, *args, **kwargs) # handle view returning httpresponse instead of string. # this will allow more customizability if some functions return # and others return httpresponse objects. if isinstance(response, HttpResponse): if isinstance(response, SimpleTemplateResponse): response.render() content = response.content elif isinstance(response, basestring): content = response else: print type(response) content = '' twilio_response = twilio.twiml.Response() twilio_response.message(msg=content, to=request.session['phone_num'], sender=PLIVO_NUMBER) response = HttpResponse(content=str(twilio_response)) return response
def make_result_list(self): # Get search parameters from the query string. self.base_queryset = self.queryset() self.list_queryset = self.get_list_queryset() self.ordering_field_columns = self.get_ordering_field_columns() self.paginator = self.get_paginator() # Get the number of objects, with admin filters applied. self.result_count = self.paginator.count # Get the total number of objects, with no admin filters applied. # Perform a slight optimization: Check to see whether any filters were # given. If not, use paginator.hits to calculate the number of objects, # because we've already done paginator.hits and the value is cached. if not self.list_queryset.query.where: self.full_result_count = self.result_count else: self.full_result_count = self.base_queryset.count() self.can_show_all = self.result_count <= self.list_max_show_all self.multi_page = self.result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and self.can_show_all) or not self.multi_page: self.result_list = self.list_queryset._clone() else: try: self.result_list = self.paginator.page( self.page_num + 1).object_list except InvalidPage: if ERROR_FLAG in list(self.request.GET.keys()): return SimpleTemplateResponse('xadmin/views/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(self.request.path + '?' + ERROR_FLAG + '=1') self.has_more = self.result_count > ( self.list_per_page * self.page_num + len(self.result_list))
def response_add(self, request, obj, post_url_continue=None): """ Determines the HttpResponse for the add_view stage. """ opts = obj._meta pk_value = obj._get_pk_val() preserved_filters = self.get_preserved_filters(request) msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)} # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: return SimpleTemplateResponse('admin/popup_response.html', { 'pk_value': escape(pk_value), 'obj': escapejs(obj) }) elif "_continue" in request.POST: msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) if post_url_continue is None: post_url_continue = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), args=(pk_value,), current_app=self.admin_site.name) post_url_continue = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url_continue) return HttpResponseRedirect(post_url_continue) elif "_addanother" in request.POST: msg = _('The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url) return HttpResponseRedirect(redirect_url) else: msg = _('The %(name)s "%(obj)s" was added successfully.') % msg_dict self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_add(request, obj)
def index(request): # if the user is not logged in, show main page if request.user.is_authenticated: return redirect('questions') return SimpleTemplateResponse('website/index.html')
def unauthorized_response(): result = SimpleTemplateResponse(template="lti_launch_failure.html") result.status_code = 401 result['WWW-Authenticate'] = 'OAuth realm=""' return result