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
python类RequestContext()的实例源码
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 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 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 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 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 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)