def get(self, request): # No query if 'q' not in request.GET: return render(request, 'search.html', { 'form': SearchForm(), }) form = SearchForm(request.GET) results = [] if form.is_valid(): if form.cleaned_data['obj_type']: # Searching for a single type of object obj_types = [form.cleaned_data['obj_type']] else: # Searching all object types obj_types = SEARCH_TYPES.keys() for obj_type in obj_types: queryset = SEARCH_TYPES[obj_type]['queryset'].restrict( request.user, 'view') filterset = SEARCH_TYPES[obj_type]['filterset'] table = SEARCH_TYPES[obj_type]['table'] url = SEARCH_TYPES[obj_type]['url'] # Construct the results table for this object type filtered_queryset = filterset({ 'q': form.cleaned_data['q'] }, queryset=queryset).qs table = table(filtered_queryset, orderable=False) table.paginate(per_page=SEARCH_MAX_RESULTS) if table.page: results.append({ 'name': queryset.model._meta.verbose_name_plural, 'table': table, 'url': f"{reverse(url)}?q={form.cleaned_data.get('q')}" }) return render(request, 'search.html', { 'form': form, 'results': results, })
def get(self, request): form = SearchForm(request.GET) results = [] if form.is_valid(): # If an object type has been specified, redirect to the dedicated view for it if form.cleaned_data['obj_type']: object_type = form.cleaned_data['obj_type'] url = reverse(SEARCH_TYPES[object_type]['url']) return redirect(f"{url}?q={form.cleaned_data['q']}") for obj_type in SEARCH_TYPES.keys(): queryset = SEARCH_TYPES[obj_type]['queryset'].restrict( request.user, 'view') filterset = SEARCH_TYPES[obj_type]['filterset'] table = SEARCH_TYPES[obj_type]['table'] url = SEARCH_TYPES[obj_type]['url'] # Construct the results table for this object type filtered_queryset = filterset({ 'q': form.cleaned_data['q'] }, queryset=queryset).qs table = table(filtered_queryset, orderable=False) table.paginate(per_page=SEARCH_MAX_RESULTS) if table.page: results.append({ 'name': queryset.model._meta.verbose_name_plural, 'table': table, 'url': f"{reverse(url)}?q={form.cleaned_data.get('q')}" }) return render(request, 'search.html', { 'form': form, 'results': results, })
from typing import Dict from netbox.forms import SearchForm from django import template register = template.Library() search_form = SearchForm() @register.inclusion_tag("search/searchbar.html") def search_options() -> Dict: """Provide search options to template.""" return {"options": search_form.options}
def get(self, request): connected_consoleports = ConsolePort.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False) connected_powerports = PowerPort.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False) connected_interfaces = Interface.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False, pk__lt=F('_path__destination_id')) # Report Results report_content_type = ContentType.objects.get(app_label='extras', model='report') report_results = JobResult.objects.filter( obj_type=report_content_type, status__in=JobResultStatusChoices.TERMINAL_STATE_CHOICES).defer( 'data')[:10] stats = { # Organization 'site_count': Site.objects.restrict(request.user, 'view').count(), 'location_count': Location.objects.restrict(request.user, 'view').count(), 'tenant_count': Tenant.objects.restrict(request.user, 'view').count(), # DCIM 'rack_count': Rack.objects.restrict(request.user, 'view').count(), 'devicetype_count': DeviceType.objects.restrict(request.user, 'view').count(), 'device_count': Device.objects.restrict(request.user, 'view').count(), 'interface_connections_count': connected_interfaces.count(), 'cable_count': Cable.objects.restrict(request.user, 'view').count(), 'console_connections_count': connected_consoleports.count(), 'power_connections_count': connected_powerports.count(), 'powerpanel_count': PowerPanel.objects.restrict(request.user, 'view').count(), 'powerfeed_count': PowerFeed.objects.restrict(request.user, 'view').count(), # IPAM 'vrf_count': VRF.objects.restrict(request.user, 'view').count(), 'aggregate_count': Aggregate.objects.restrict(request.user, 'view').count(), 'prefix_count': Prefix.objects.restrict(request.user, 'view').count(), 'ipaddress_count': IPAddress.objects.restrict(request.user, 'view').count(), 'vlan_count': VLAN.objects.restrict(request.user, 'view').count(), # Circuits 'provider_count': Provider.objects.restrict(request.user, 'view').count(), 'circuit_count': Circuit.objects.restrict(request.user, 'view').count(), # Secrets 'secret_count': Secret.objects.restrict(request.user, 'view').count(), # Virtualization 'cluster_count': Cluster.objects.restrict(request.user, 'view').count(), 'virtualmachine_count': VirtualMachine.objects.restrict(request.user, 'view').count(), } changelog = ObjectChange.objects.restrict(request.user, 'view').prefetch_related( 'user', 'changed_object_type') # Check whether a new release is available. (Only for staff/superusers.) new_release = None if request.user.is_staff or request.user.is_superuser: latest_release, release_url = get_latest_release() if isinstance(latest_release, version.Version): current_version = version.parse(settings.VERSION) if latest_release > current_version: new_release = { 'version': str(latest_release), 'url': release_url, } return render( request, self.template_name, { 'search_form': SearchForm(), 'stats': stats, 'report_results': report_results, 'changelog': changelog[:15], 'new_release': new_release, })
def get(self, request): if settings.LOGIN_REQUIRED and not request.user.is_authenticated: return redirect("login") connected_consoleports = ConsolePort.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False) connected_powerports = PowerPort.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False) connected_interfaces = Interface.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False, pk__lt=F('_path__destination_id')) # Report Results report_content_type = ContentType.objects.get(app_label='extras', model='report') report_results = JobResult.objects.filter( obj_type=report_content_type, status__in=JobResultStatusChoices.TERMINAL_STATE_CHOICES).defer( 'data')[:10] def build_stats(): org = ( ("dcim.view_site", "Sites", Site.objects.restrict(request.user, 'view').count), ("tenancy.view_tenant", "Tenants", Tenant.objects.restrict(request.user, 'view').count), ) dcim = ( ("dcim.view_rack", "Racks", Rack.objects.restrict(request.user, 'view').count), ("dcim.view_devicetype", "Device Types", DeviceType.objects.restrict(request.user, 'view').count), ("dcim.view_device", "Devices", Device.objects.restrict(request.user, 'view').count), ) ipam = (("ipam.view_vrf", "VRFs", VRF.objects.restrict(request.user, 'view').count), ("ipam.view_aggregate", "Aggregates", Aggregate.objects.restrict(request.user, 'view').count), ("ipam.view_prefix", "Prefixes", Prefix.objects.restrict(request.user, 'view').count), ("ipam.view_iprange", "IP Ranges", IPRange.objects.restrict(request.user, 'view').count), ("ipam.view_ipaddress", "IP Addresses", IPAddress.objects.restrict(request.user, 'view').count), ("ipam.view_vlan", "VLANs", VLAN.objects.restrict(request.user, 'view').count)) circuits = ( ("circuits.view_provider", "Providers", Provider.objects.restrict(request.user, 'view').count), ("circuits.view_circuit", "Circuits", Circuit.objects.restrict(request.user, 'view').count), ) virtualization = ( ("virtualization.view_cluster", "Clusters", Cluster.objects.restrict(request.user, 'view').count), ("virtualization.view_virtualmachine", "Virtual Machines", VirtualMachine.objects.restrict(request.user, 'view').count), ) connections = ( ("dcim.view_cable", "Cables", Cable.objects.restrict(request.user, 'view').count), ("dcim.view_consoleport", "Console", connected_consoleports.count), ("dcim.view_interface", "Interfaces", connected_interfaces.count), ("dcim.view_powerport", "Power Connections", connected_powerports.count), ) power = ( ("dcim.view_powerpanel", "Power Panels", PowerPanel.objects.restrict(request.user, 'view').count), ("dcim.view_powerfeed", "Power Feeds", PowerFeed.objects.restrict(request.user, 'view').count), ) sections = ( ("Organization", org, "domain"), ("IPAM", ipam, "counter"), ("Virtualization", virtualization, "monitor"), ("Inventory", dcim, "server"), ("Connections", connections, "cable-data"), ("Circuits", circuits, "transit-connection-variant"), ("Power", power, "flash"), ) stats = [] for section_label, section_items, icon_class in sections: items = [] for perm, item_label, get_count in section_items: app, scope = perm.split(".") url = ":".join((app, scope.replace("view_", "") + "_list")) item = { "label": item_label, "count": None, "url": url, "disabled": True, "icon": icon_class, } if request.user.has_perm(perm): item["count"] = get_count() item["disabled"] = False items.append(item) stats.append((section_label, items, icon_class)) return stats # Compile changelog table changelog = ObjectChange.objects.restrict( request.user, 'view').prefetch_related('user', 'changed_object_type')[:10] changelog_table = ObjectChangeTable(changelog) # Check whether a new release is available. (Only for staff/superusers.) new_release = None if request.user.is_staff or request.user.is_superuser: latest_release = cache.get('latest_release') if latest_release: release_version, release_url = latest_release if release_version > version.parse(settings.VERSION): new_release = { 'version': str(latest_release), 'url': release_url, } return render( request, self.template_name, { 'search_form': SearchForm(), 'stats': build_stats(), 'report_results': report_results, 'changelog_table': changelog_table, 'new_release': new_release, })
def get(self, request): if settings.LOGIN_REQUIRED and not request.user.is_authenticated: return redirect("login") connected_consoleports = ConsolePort.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False) connected_powerports = PowerPort.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False) connected_interfaces = Interface.objects.restrict( request.user, 'view').prefetch_related('_path').filter( _path__destination_id__isnull=False, pk__lt=F('_path__destination_id')) # Report Results report_content_type = ContentType.objects.get(app_label='extras', model='report') report_results = JobResult.objects.filter( obj_type=report_content_type, status__in=JobResultStatusChoices.TERMINAL_STATE_CHOICES).defer( 'data')[:10] def build_stats(): org = ( ("dcim.view_site", "Адреса", Site.objects.restrict(request.user, 'view').count), ("tenancy.view_tenant", "Учреждения", Tenant.objects.restrict(request.user, 'view').count), ) dcim = ( ("dcim.view_rack", "Стойки", Rack.objects.restrict(request.user, 'view').count), ("dcim.view_devicetype", "Типы устройств", DeviceType.objects.restrict(request.user, 'view').count), ("dcim.view_device", "Устройства", Device.objects.restrict(request.user, 'view').count), ) ipam = (("ipam.view_vrf", "VRF", VRF.objects.restrict(request.user, 'view').count), ("ipam.view_aggregate", "Сети", Aggregate.objects.restrict(request.user, 'view').count), ("ipam.view_prefix", "Подсети", Prefix.objects.restrict(request.user, 'view').count), ("ipam.view_iprange", "IP диапазоны", IPRange.objects.restrict(request.user, 'view').count), ("ipam.view_ipaddress", "IP адреса", IPAddress.objects.restrict(request.user, 'view').count), ("ipam.view_vlan", "VLAN", VLAN.objects.restrict(request.user, 'view').count)) circuits = ( ("circuits.view_provider", "Поставщики услуг", Provider.objects.restrict(request.user, 'view').count), ("circuits.view_circuit", "Внешние каналы", Circuit.objects.restrict(request.user, 'view').count), ) virtualization = ( ("virtualization.view_cluster", "Кластеры", Cluster.objects.restrict(request.user, 'view').count), ("virtualization.view_virtualmachine", "Виртуальные машины", VirtualMachine.objects.restrict(request.user, 'view').count), ) connections = ( ("dcim.view_cable", "Кабели", Cable.objects.restrict(request.user, 'view').count), ("dcim.view_consoleport", "Консоли", connected_consoleports.count), ("dcim.view_interface", "Интерфейсы", connected_interfaces.count), ("dcim.view_powerport", "Подключение питания", connected_powerports.count), ) power = ( ("dcim.view_powerpanel", "Силовые панели", PowerPanel.objects.restrict(request.user, 'view').count), ("dcim.view_powerfeed", "Электропитание", PowerFeed.objects.restrict(request.user, 'view').count), ) wireless = ( ("wireless.view_wirelesslan", "Беспроводные LAN", WirelessLAN.objects.restrict(request.user, 'view').count), ("wireless.view_wirelesslink", "Беспроводные соединения", WirelessLink.objects.restrict(request.user, 'view').count), ) sections = ( ("Структура", org, "domain"), ("IP адреса", ipam, "counter"), ("Виртуализация", virtualization, "monitor"), ("Устройства", dcim, "server"), ("Circuits", circuits, "transit-connection-variant"), ("Внешние каналы", connections, "cable-data"), ("Электропитание", power, "flash"), ("Беспроводные соединения", wireless, "wifi"), ) stats = [] for section_label, section_items, icon_class in sections: items = [] for perm, item_label, get_count in section_items: app, scope = perm.split(".") url = ":".join((app, scope.replace("view_", "") + "_list")) item = { "label": item_label, "count": None, "url": url, "disabled": True, "icon": icon_class, } if request.user.has_perm(perm): item["count"] = get_count() item["disabled"] = False items.append(item) stats.append((section_label, items, icon_class)) return stats # Compile changelog table changelog = ObjectChange.objects.restrict( request.user, 'view').prefetch_related('user', 'changed_object_type')[:10] changelog_table = ObjectChangeTable(changelog) # Check whether a new release is available. (Only for staff/superusers.) new_release = None if request.user.is_staff or request.user.is_superuser: latest_release = cache.get('latest_release') if latest_release: release_version, release_url = latest_release if release_version > version.parse(settings.VERSION): new_release = { 'version': str(release_version), 'url': release_url, } return render( request, self.template_name, { 'search_form': SearchForm(), 'stats': build_stats(), 'report_results': report_results, 'changelog_table': changelog_table, 'new_release': new_release, })