def manual_updates_required(request, updates): """Render a page showing required updates that the admin must make. Args: request (django.http.HttpRequest): The HTTP request from the client. updates (list): The list of required updates to display on the page. Returns: django.http.HttpResponse: The response to send to the client. """ return render( request=request, template_name='admin/manual_updates_required.html', context={ 'updates': [ render_to_string(template_name=update_template_name, context=extra_context, request=request) for update_template_name, extra_context in updates ], })
def configure_extension(request, ext_class, form_class, extension_manager, template_name='extensions/configure_extension.html'): extension = extension_manager.get_enabled_extension(ext_class.id) if not extension or not extension.is_configurable: raise Http404 if request.method == 'POST': form = form_class(extension, request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(request.path + '?saved=1') else: form = form_class(extension) return render( request, template_name, { 'extension': extension, 'form': form, 'saved': request.GET.get('saved', 0), })
def view_feed(request, url, template_name="feedview/feed-page.html", cache_expiration=DEFAULT_EXPIRATION, extra_context={}): """ Renders an RSS or Atom feed using the given template. This will use a cached copy if available in order to reduce hits to the server. """ def fetch_feed(): import feedparser data = urlopen(url).read() parser = feedparser.parse(data) context = { 'parser': parser, } context.update(extra_context) return render_to_string(template_name, context, request) try: return HttpResponse(cache_memoize("feed-%s" % url, fetch_feed, cache_expiration, force_overwrite=('reload' in request.GET))) except (URLError, http_client.HTTPException) as e: context = { 'error': e, } context.update(extra_context) return render(request, template_name, context)
def rbtools_setup(self, request, repository_id): repository = get_object_or_404(Repository, pk=repository_id) return render( request=request, template_name='admin/scmtools/repository/rbtools_setup.html', context={ 'repository': repository, 'reviewboard_url': get_server_url( local_site=repository.local_site), })
def security(request, template_name="admin/security.html"): """Run security checks and report the results.""" runner = SecurityCheckRunner() results = runner.run() return render(request=request, template_name=template_name, context={ 'test_results': results, 'title': _('Security Checklist'), })
def extension_list(request, extension_manager, template_name='extensions/extension_list.html'): if request.method == 'POST': if 'full-reload' in request.POST: extension_manager.load(full_reload=True) return HttpResponseRedirect('.') else: # Refresh the extension list. extension_manager.load() return render(request, template_name)
def extension_list(request, extension_manager, template_name='extensions/admin/extension_list.html'): if request.method == 'POST': if 'full-reload' in request.POST: extension_manager.load(full_reload=True) return HttpResponseRedirect('.') else: # Refresh the extension list. extension_manager.load() return render(request, template_name)
def site_settings(request, form_class=SiteSettingsForm, template_name='siteconfig/settings.html', extra_context={}): """A view for customizing the site configuration's settings. This will make use of the provided form class and template, handling loading and saving any site configuration settings. Args: request (django.http.HttpRequest): The HTTP request for the view. form_class (type, optional): The form class to use for editing the settings. This should be either :py:class:`~djblets.siteconfig.forms.SiteSettingsForm` or a subclass of it. template_name (unicode, optional): The template to render for the view. extra_context (dict, optional): Extra context variables to pass to the template. Returns: django.http.HttpResponse: The response containing the page. """ siteconfig = SiteConfiguration.objects.get_current() if request.method == 'POST': form = form_class(siteconfig, request.POST, request.FILES, request=request) if form.is_valid(): form.save() return HttpResponseRedirect('.?saved=1') else: form = form_class(siteconfig, request=request) context = { 'form': form, 'saved': request.GET.get('saved', 0) } context.update(extra_context) return render(request, template_name, context)
def server_log(request, template_name='log/log.html'): """Displays the server log.""" # First check if logging is even configured. If it's not, just return # a 404. if (not getattr(settings, "LOGGING_ENABLED", False) or not getattr(settings, "LOGGING_DIRECTORY", None)): raise Http404() requested_levels = [] # Get the list of levels to show. if 'levels' in request.GET: requested_levels = request.GET.get('levels').split(',') # Get the timestamp ranges. from_timestamp = parse_timestamp('%Y-%m-%d', request.GET.get('from')) to_timestamp = parse_timestamp('%Y-%m-%d', request.GET.get('to')) if from_timestamp: from_timestamp = from_timestamp.date() if to_timestamp: to_timestamp = to_timestamp.date() # Get the filters to show. filtersets = get_log_filtersets(request, requested_levels, from_timestamp, to_timestamp) # Grab the lines from the log file. log_lines = iter_log_lines(from_timestamp, to_timestamp, requested_levels) # Figure out the sorting sort_type = request.GET.get('sort', 'asc') if sort_type == 'asc': reverse_sort_type = 'desc' else: reverse_sort_type = 'asc' log_lines = reversed(list(log_lines)) return render(request, template_name, { 'log_lines': log_lines, 'filtersets': filtersets, 'sort_url': build_query_string(request, {'sort': reverse_sort_type}), 'sort_type': sort_type, })
def dashboard(request, template_name="admin/dashboard.html"): """Display the administration dashboard. This is the entry point to the admin site, containing news updates and useful administration tasks. """ return render(request=request, template_name=template_name, context={ 'widgets': primary_widgets + secondary_widgets, 'root_path': reverse('admin:index'), 'title': _('Admin Dashboard'), 'page_model_attrs': { 'supportData': serialize_support_data(request, force_is_admin=True), }, })
def site_settings(request, form_class=SiteSettingsForm, template_name='siteconfig/settings.html', extra_context={}): """A view for customizing the site configuration's settings. This will make use of the provided form class and template, handling loading and saving any site configuration settings. Args: request (django.http.HttpRequest): The HTTP request for the view. form_class (type, optional): The form class to use for editing the settings. This should be either :py:class:`~djblets.siteconfig.forms.SiteSettingsForm` or a subclass of it. template_name (unicode, optional): The template to render for the view. extra_context (dict, optional): Extra context variables to pass to the template. Returns: django.http.HttpResponse: The response containing the page. """ siteconfig = SiteConfiguration.objects.get_current() if request.method == 'POST': form = form_class(siteconfig, request.POST, request.FILES, request=request) if form.is_valid(): form.save() return HttpResponseRedirect('.?saved=1') else: form = form_class(siteconfig, request=request) context = {'form': form, 'saved': request.GET.get('saved', 0)} context.update(extra_context) return render(request, template_name, context)
def cache_stats(request, template_name="admin/cache_stats.html"): """Display statistics on the cache. This includes such pieces of information as memory used, cache misses, and uptime. """ cache_stats = get_cache_stats() cache_info = settings.CACHES[DEFAULT_FORWARD_CACHE_ALIAS] return render(request=request, template_name=template_name, context={ 'cache_hosts': cache_stats, 'cache_backend': cache_info['BACKEND'], 'title': _('Server Cache'), 'root_path': reverse('admin:index'), })
def _check(request, local_site_name=None, *args, **kwargs): if local_site_name: if not request.local_site: raise Http404 local_site = request.local_site if not local_site.is_mutable_by(request.user): return render(request=request, template_name='permission_denied.html', status=403) else: local_site = None return view_func(request, local_site_name=local_site_name, local_site=local_site, *args, **kwargs)
def decorated(request, *args, **kwargs): if not request.user.is_authenticated(): return login(request, template_name='admin/login.html', authentication_form=AdminAuthenticationForm, extra_context={ 'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path(), }) if not (request.user.is_active and request.user.is_superuser): return render(request=request, template_name='admin/permission_denied.html', context={ 'user': request.user, }) return view(request, *args, **kwargs)
def _check(request, local_site_name=None, *args, **kwargs): if local_site_name: if not request.local_site: raise Http404 local_site = request.local_site if not local_site.is_accessible_by(request.user): if local_site.public or request.user.is_authenticated(): return render(request=request, template_name='permission_denied.html', status=403) else: return HttpResponseRedirect( '%s?next=%s' % (reverse('login'), request.get_full_path())) else: local_site = None return view_func(request, local_site=local_site, *args, **kwargs)
def dashboard(request, template_name="admin/dashboard.html"): """Display the administration dashboard. This is the entry point to the admin site, containing news updates and useful administration tasks. """ profile = request.user.get_profile() profile_data = profile.extra_data selected_primary_widgets, unselected_primary_widgets = \ _get_widget_selections(primary_widgets, profile_data.get('primary_widget_selections')) selected_secondary_widgets, unselected_secondary_widgets = \ _get_widget_selections(secondary_widgets, profile_data.get('secondary_widget_selections')) sorted_primary_widgets = _sort_widgets( selected_primary_widgets, profile_data.get('primary_widget_positions') ) sorted_secondary_widgets = _sort_widgets( selected_secondary_widgets, profile_data.get('secondary_widget_positions') ) return render( request=request, template_name=template_name, context={ 'primary_widgets': primary_widgets, 'root_path': reverse('admin:index'), 'secondary_widgets': secondary_widgets, 'selected_primary_widgets': sorted_primary_widgets, 'selected_secondary_widgets': sorted_secondary_widgets, 'support_data': serialize_support_data(request, True), 'title': _('Admin Dashboard'), 'unselected_primary_widgets': unselected_primary_widgets, 'unselected_secondary_widgets': unselected_secondary_widgets, })
def ssh_settings(request, template_name='admin/ssh_settings.html'): """Render the SSH settings page.""" client = SSHClient() key = client.get_user_key() if request.method == 'POST': form = SSHSettingsForm(request.POST, request.FILES) if form.is_valid(): if form.did_request_delete() and client.get_user_key() is not None: try: form.delete() return HttpResponseRedirect('.') except Exception as e: logger.error('Deleting SSH key failed: %s' % e) else: try: form.create(request.FILES) return HttpResponseRedirect('.') except Exception as e: # Fall through. It will be reported inline and in the log. logger.error('Uploading SSH key failed: %s' % e) else: form = SSHSettingsForm() if key: fingerprint = humanize_key(key) else: fingerprint = None return render(request=request, template_name=template_name, context={ 'has_file_field': True, 'key': key, 'fingerprint': fingerprint, 'public_key': client.get_public_key(key).replace('\n', ''), 'form': form, })
def configure_extension(request, ext_class, form_class, extension_manager, template_name='extensions/configure_extension.html'): extension = extension_manager.get_enabled_extension(ext_class.id) if not extension or not extension.is_configurable: raise Http404 if request.method == 'POST': form = form_class(extension, request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(request.path + '?saved=1') else: form = form_class(extension) return render(request, template_name, { 'extension': extension, 'form': form, 'saved': request.GET.get('saved', 0), })
def view_feed(request, url, template_name="feedview/feed-page.html", cache_expiration=DEFAULT_EXPIRATION, extra_context={}): """ Renders an RSS or Atom feed using the given template. This will use a cached copy if available in order to reduce hits to the server. """ def fetch_feed(): import feedparser data = urlopen(url).read() parser = feedparser.parse(data) context = { 'parser': parser, } context.update(extra_context) return render_to_string(template_name, context, request) try: return HttpResponse( cache_memoize("feed-%s" % url, fetch_feed, cache_expiration, force_overwrite=('reload' in request.GET))) except (URLError, http_client.HTTPException) as e: context = { 'error': e, } context.update(extra_context) return render(request, template_name, context)
def edit_oauth_app(request, app_id=None): """Create or edit an OAuth2 application. Args: request (django.http.HttpRequest): The current HTTP request. app_id (int, optional): The ID of the application to edit. If this argument is ``None`` a new application will be edited. Returns: django.http.HttpResponse: The rendered view. """ # If we import this at global scope, it will cause issues with admin sites # being automatically registered. from reviewboard.oauth.admin import ApplicationAdmin if app_id: app = get_object_or_404( Application, pk=app_id, user=request.user, ) form_cls = UserApplicationChangeForm fieldsets = ApplicationAdmin.fieldsets else: app = None form_cls = UserApplicationCreationForm fieldsets = ApplicationAdmin.add_fieldsets if request.method == 'POST': form_data = request.POST.copy() form = form_cls(user=request.user, data=form_data, initial=None, instance=app) if form.is_valid(): app = form.save() if app_id is not None: next_url = OAuth2Page.get_absolute_url() else: next_url = reverse('edit-oauth-app', args=(app.pk, )) return HttpResponseRedirect(next_url) else: form = form_cls(user=request.user, data=None, initial=None, instance=app) # Show a warning at the top of the form when the form is disabled for # security. # # We don't need to worry about full_clean not being called (which would # be if we went through form.errors) because this form will never be # saved. if app and app.is_disabled_for_security: form._errors = ErrorDict({ '__all__': form.error_class([form.DISABLED_FOR_SECURITY_ERROR], ), }) return render(request=request, template_name='accounts/edit_oauth_app.html', context={ 'app': app, 'form': form, 'fieldsets': filter_fieldsets(form=form_cls, fieldsets=fieldsets), 'oauth2_page_url': OAuth2Page.get_absolute_url(), 'request': request, })
def register(request, next_page, form_class=RegistrationForm, extra_context=None, initial_values=None, form_kwargs=None, template_name="accounts/register.html"): """Handle registration of a new user. This works along with :py:class:`djblets.auth.forms.RegistrationForm` to register a new user. It will display a registration form, validate the user's new information, and then log them in. The registration form, next page, and context can all be customized by the caller. Args: request (HttpRequest): The HTTP request from the client. next_page (unicode): The URL to navigate to once registration is successful. form_class (Form subclass): The form that will handle registration, field validation, and creation of the user. extra_context (dict): Extra context variables to pass to the template when rendering. initial_values (dict): Initial values to set on the form when it is rendered. form_kwargs (dict): Additional keyword arguments to pass to the form class during instantiation. template_name (unicode): The name of the template containing the registration form. Returns: HttpResponse: The page's rendered response or redirect. """ if initial_values is None: initial_values = {} if form_kwargs is None: form_kwargs = {} if request.method == 'POST': form = form_class(data=request.POST, request=request, **form_kwargs) form.full_clean() validate_test_cookie(form, request) if form.is_valid(): user = form.save() if user: user = auth.authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password1']) assert user auth.login(request, user) try: request.session.delete_test_cookie() except KeyError: # Do nothing pass # Other components can listen to this signal to # perform additional tasks when a new user registers user_registered.send(sender=None, user=request.user) return HttpResponseRedirect(next_page) else: form = form_class(initial=initial_values, request=request, **form_kwargs) request.session.set_test_cookie() context = { 'form': form, } if extra_context: context.update(extra_context) return render(request, template_name, context)
def admin_dashboard_view(request): """Display the administration dashboard. This is the entry point to the admin site, containing news updates and useful administration tasks. Args: request (django.http.HttpRequest): The HTTP request from the client. Returns: django.http.HttpResponse: The resulting HTTP response for the view. """ widgets_info = [] widgets_html = [] for widget_cls in admin_widgets_registry: try: widget = widget_cls() if not widget.can_render(request): continue if widget.dom_id is None: widget.dom_id = 'admin-widget-%s' % widget.widget_id widget_info = { 'id': widget.widget_id, 'domID': widget.dom_id, 'viewClass': widget.js_view_class, 'modelClass': widget.js_model_class, } js_view_options = widget.get_js_view_options(request) js_model_attrs = widget.get_js_model_attrs(request) js_model_options = widget.get_js_model_options(request) if js_view_options: widget_info['viewOptions'] = js_view_options if js_model_attrs: widget_info['modelAttrs'] = js_model_attrs if js_model_options: widget_info['modelOptions'] = js_model_options widget_html = widget.render(request) except Exception as e: logger.exception('Error setting up administration widget %r: %s', widget_cls, e) continue widgets_info.append(widget_info) widgets_html.append((widget_html, )) return render(request=request, template_name='admin/dashboard.html', context={ 'page_model_attrs': { 'supportData': serialize_support_data(request, force_is_admin=True), 'widgetsData': widgets_info, }, 'title': _('Admin Dashboard'), 'widgets_html': format_html_join('', '{0}', widgets_html), })