我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用django.template.context.RequestContext()。
def render_add_type_form(self, request, context, form_url=''): """ Render the page type choice form. """ opts = self.model._meta app_label = opts.app_label context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': mark_safe(form_url), 'opts': opts, 'add': True, 'save_on_top': self.save_on_top, }) if hasattr(self.admin_site, 'root_path'): context['root_path'] = self.admin_site.root_path # Django < 1.4 context_instance = RequestContext(request, current_app=self.admin_site.name) return render_to_response(self.add_type_template or [ "admin/%s/%s/add_type_form.html" % (app_label, opts.object_name.lower()), "admin/%s/add_type_form.html" % app_label, "admin/polymorphic/add_type_form.html", # added default here "admin/add_type_form.html" ], context, context_instance=context_instance)
def index(request): """Controller for vlan landing page and search""" vlans = Vlan.objects.none() navpath = get_path() if "query" in request.GET: searchform = VlanSearchForm(request.GET) if searchform.is_valid(): navpath = get_path([('Search for "%s"' % request.GET['query'], )]) vlans = process_searchform(searchform) else: searchform = VlanSearchForm() LOGGER.debug(vlans) return render_to_response("info/vlan/base.html", {'navpath': navpath, 'title': create_title(navpath), 'form': searchform, 'vlans': vlans}, context_instance=RequestContext(request))
def handle(self, request, q): node_q = Node.objects.filter(name=q) if node_q.count() == 1: return HttpResponseRedirect(reverse('graphs', args=(node_q[0].group, node_q[0].name))) node_q = Node.objects.filter(name__startswith=q) if node_q.count() == 1: return HttpResponseRedirect(reverse('graphs', args=(node_q[0].group, node_q[0].name))) group_q = Node.objects.filter(group=q) if group_q.exists(): return HttpResponseRedirect(reverse('group_nodes', args=(group_q[0].group, ))) response = render_to_response('not_found.html', {}, RequestContext(request)) response.status_code = 404 return response
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)
def get_context_dict(context): """ Contexts in django version 1.9+ must be dictionaries. As xadmin has a legacy with older versions of django, the function helps the transition by converting the [RequestContext] object to the dictionary when necessary. :param context: RequestContext :return: dict """ if isinstance(context, RequestContext): ctx = context.flatten() else: ctx = context return ctx
def get_context_dict(context): """ Contexts in django version 1.9+ must be dictionaries. As xadmin has a legacy with older versions of django, the function helps the transition by converting the [RequestContext] object to the dictionary when necessary. :param context: RequestContext :return: dict """ if isinstance(context, RequestContext): ctx = {} map(ctx.update, context.dicts) else: ctx = context return ctx
def defaultView(request): return render_to_response('bootstrap/base.html', context_instance=RequestContext(request))
def render_to_temporary_file(template, context, request=None, mode='w+b', bufsize=-1, suffix='.html', prefix='tmp', dir=None, delete=True): if django.VERSION < (1, 8): # If using a version of Django prior to 1.8, ensure ``context`` is an # instance of ``Context`` if not isinstance(context, Context): if request: context = RequestContext(request, context) else: context = Context(context) content = template.render(context) else: content = template.render(context, request) content = smart_text(content) content = make_absolute_paths(content) try: # Python3 has 'buffering' arg instead of 'bufsize' tempfile = NamedTemporaryFile(mode=mode, buffering=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) except TypeError: tempfile = NamedTemporaryFile(mode=mode, bufsize=bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete) try: tempfile.write(content.encode('utf-8')) tempfile.flush() return tempfile except: # Clean-up tempfile if an Exception is raised. tempfile.close() raise
def get(self, request, *args, **kwargs): form = self.form_class() variables = RequestContext(request, {'form': form}) return render_to_response(self.template_name, variables, )
def widget(self): context = {'widget_id': self.id, 'widget_title': self.title, 'widget_icon': self.widget_icon, 'widget_type': self.widget_type, 'form': self, 'widget': self} self.context(context) return loader.render_to_string(self.template, context, context_instance=RequestContext(self.request))
def render_template(self, request, form, previous_fields, step, context=None): """ Renders the template for the given step, returning an HttpResponse object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use get_template() instead. The template will be rendered with the following context: step_field -- The name of the hidden field containing the step. step0 -- The current step (zero-based). step -- The current step (one-based). step_count -- The total number of steps. form -- The Form instance for the current step (either empty or with errors). previous_fields -- A string representing every previous data field, plus hashes for completed forms, all in the form of hidden fields. Note that you'll need to run this through the "safe" template filter, to prevent auto-escaping, because it's raw HTML. """ context = context or {} context.update(self.extra_context) return render_to_response(self.get_template(step), dict(context, step_field=self.step_field_name, step0=step, step=step + 1, step_count=self.num_steps(), form=form, previous_fields=previous_fields ), context_instance=RequestContext(request))
def render_to_string(request, result, default_template, prefix=None, template_ext='html'): templates = [default_template] dictionary = None # ???? # {'var': value ...} if isinstance(result, dict): dictionary = result # 'template' or '/root_template' elif isinstance(result, basestring): templates = [result] # 'template1', 'template2' ... # 'template', {'var': value ...} # 'template1', 'template2', ... {'var': value ...} elif isinstance(result, tuple): # ????????? if isinstance(result[-1], dict): templates = list(result[:-1]) dictionary = result[-1] else: templates = list(result) if getattr(request, 'is_mobile', False): templates = [t + '.mobile' for t in templates] + templates for i in xrange(0, len(templates)): if templates[i].startswith('/'): templates[i] = templates[i][1:] elif prefix: templates[i] = prefix + templates[i] templates[i] += '.' + template_ext return _render_to_string(templates, dictionary, RequestContext(request))
def dispatch(self, request, *args, **kwargs): # Let logged in super users continue if not request.user.is_anonymous() and not request.user.is_superuser: return redirect('wiki:root') # If account handling is disabled, don't go here if not settings.ACCOUNT_HANDLING: return redirect(settings.SIGNUP_URL) # Allow superusers to use signup page... if not request.user.is_superuser and not settings.ACCOUNT_SIGNUP_ALLOWED: c = RequestContext( request, { 'error_msg': _('Account signup is only allowed for administrators.'), }) return render_to_response("wiki/error.html", context=c) return super(Signup, self).dispatch(request, *args, **kwargs)
def vlan_details(request, vlanid): """Render details for a vlan""" vlan = get_object_or_404(Vlan.objects.select_related('prefix'), pk=vlanid) prefixes = sorted(vlan.prefix_set.all(), key=methodcaller('get_prefix_size')) has_v6 = False has_v4 = False for prefix in prefixes: version = IP(prefix.net_address).version() if version == 6: has_v6 = True elif version == 4: has_v4 = True navpath = get_path([(str(vlan), '')]) return render_to_response('info/vlan/vlandetails.html', {'vlan': vlan, 'prefixes': prefixes, 'gwportprefixes': find_gwportprefixes(vlan), 'navpath': navpath, 'has_v4': has_v4, 'has_v6': has_v6, 'title': create_title(navpath)}, context_instance=RequestContext(request))
def preview_get(self, request): "Displays the form" f = self.form(auto_id=self.get_auto_id(), initial=self.get_initial(request)) return render_to_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request))
def preview_post(self, request): "Validates the POST data. If valid, displays the preview page. Else, redisplays form." f = self.form(request.POST, auto_id=self.get_auto_id()) context = self.get_context(request, f) if f.is_valid(): self.process_preview(request, f, context) context['hash_field'] = self.unused_name('hash') context['hash_value'] = self.security_hash(request, f) return render_to_response(self.preview_template, context, context_instance=RequestContext(request)) else: return render_to_response(self.form_template, context, context_instance=RequestContext(request))
def post_post(self, request): "Validates the POST data. If valid, calls done(). Else, redisplays form." f = self.form(request.POST, auto_id=self.get_auto_id()) if f.is_valid(): if not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''), request, f): return self.failed_hash(request) # Security hash failed. return self.done(request, f.cleaned_data) else: return render_to_response(self.form_template, self.get_context(request, f), context_instance=RequestContext(request)) # METHODS SUBCLASSES MIGHT OVERRIDE IF APPROPRIATE ########################
def widget(self): context = {'widget_id': self.id, 'widget_title': self.title, 'widget_type': self.widget_type, 'form': self, 'widget': self} self.context(context) return loader.render_to_string(self.template, context, context_instance=RequestContext(self.request))
def home(request): return render_to_response('home.html', context=RequestContext(request))
def connections(request): global access_token return render_to_response('connections.html', context=RequestContext(request, {'access_token':access_token[0]}))
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 2.0 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.", RemovedInDjango20Warning, stacklevel=2) elif isinstance(context, Context): warnings.warn( "render() must be called with a dict, not a Context.", RemovedInDjango20Warning, stacklevel=2) else: context = make_context(context, request) return self.template.render(context)
def getClosestServersView(request): config = speedtest.getConfig() closestServers = speedtest.closestServers(config['client']) # store to db models = [] localIp = getLocalIp("speedtest.net") for server in closestServers: server["serverId"] = server.pop("id") model = SpeedtestServer().fromDict(**server) model.interfaceIp = localIp models.append(model) SpeedtestServer.objects.bulk_create(models) # filter/reorder/translate values for view title = "Speedtest.net - Closest Server" columnToName = OrderedDict ([ ("serverId", "ID"), ("name", "City"), ("url", "URL"), ("country", "Country"), ("d", "Distance [km]"), #("cc", "country code"), #("host", "host name"), ("sponsor", ""), #("url2", "url"), ("lat", "Latitude"), ("lon", "Longitude"), ]) columns = columnToName.keys() servers = [] for c in closestServers: server = OrderedDict([(columnToName[filteredColumn], c[filteredColumn]) for filteredColumn in columns]) distanceColumn = columnToName["d"] server[distanceColumn] = round(server[distanceColumn],1) servers.append(server) data = { "title": title, "tableHeader" : servers[0].keys(), "servers": servers, } return render_to_response('bootstrap/serverlist.html', data, context_instance=RequestContext(request))
def changelist_view(self, request, extra_context=None): # First load a mapping between config name and default value if not self.has_change_permission(request, None): raise PermissionDenied default_initial = ((name, default) for name, (default, help_text) in settings.CONFIG.items()) # Then update the mapping with actually values from the backend initial = dict(default_initial, **dict(config._backend.mget(settings.CONFIG.keys()))) form = ConstanceForm(initial=initial) if request.method == 'POST': form = ConstanceForm(request.POST) if form.is_valid(): form.save() # In django 1.5 this can be replaced with self.message_user messages.add_message( request, messages.SUCCESS, _('Live settings updated successfully.'), ) return HttpResponseRedirect('.') context = { 'config': [], 'title': _('Constance config'), 'app_label': 'constance', 'opts': Config._meta, 'form': form, 'media': self.media + form.media, } for name, (default, help_text) in settings.CONFIG.items(): # First try to load the value from the actual backend value = initial.get(name) # Then if the returned value is None, get the default if value is None: value = getattr(config, name) context['config'].append({ 'name': name, 'default': localize(default), 'help_text': _(help_text), 'value': localize(value), 'modified': value != default, 'form_field': form[name], }) context['config'].sort(key=itemgetter('name')) context_instance = RequestContext(request, current_app=self.admin_site.name) return render_to_response('admin/constance/change_list.html', context, context_instance=context_instance)