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)
python类RequestContext()的实例源码
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 = 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 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_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_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 get(self, request, *args, **kwargs):
form = self.form_class()
variables = RequestContext(request, {'form': form})
return render_to_response(self.template_name, variables, )
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 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 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 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 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 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 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 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 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 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 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 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 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