Esempio n. 1
0
    def get_extra_context(self, request, instance):
        vlans = (
            VLAN.objects.restrict(request.user, "view")
            .filter(group=instance)
            .prefetch_related(Prefetch("prefixes", queryset=Prefix.objects.restrict(request.user)))
        )
        vlans_count = vlans.count()
        vlans = add_available_vlans(instance, vlans)

        vlan_table = tables.VLANDetailTable(vlans)
        if request.user.has_perm("ipam.change_vlan") or request.user.has_perm("ipam.delete_vlan"):
            vlan_table.columns.show("pk")
        vlan_table.columns.hide("site")
        vlan_table.columns.hide("group")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(vlan_table)

        # Compile permissions list for rendering the object table
        permissions = {
            "add": request.user.has_perm("ipam.add_vlan"),
            "change": request.user.has_perm("ipam.change_vlan"),
            "delete": request.user.has_perm("ipam.delete_vlan"),
        }

        return {
            "first_available_vlan": instance.get_next_available_vid(),
            "bulk_querystring": f"group_id={instance.pk}",
            "vlan_table": vlan_table,
            "permissions": permissions,
            "vlans_count": vlans_count,
        }
Esempio n. 2
0
    def get(self, request, *args, **kwargs):
        """Render the home page for Nautobot."""
        registry = dict(get_commands_registry())
        logs = CommandLog.objects.all().order_by("-start_time")

        # Summarize the number of times each command/subcommand has been called
        for command_name, command_data in registry.items():
            registry[command_name]["count"] = logs.filter(
                command=command_name).count()

            for subcommand_name in command_data["subcommands"]:
                registry[command_name]["subcommands"][subcommand_name][
                    "count"] = logs.filter(command=command_name,
                                           subcommand=subcommand_name).count()

        # Support sorting, filtering, customization, and pagination of the table
        queryset = CommandLogFilter(request.GET, logs).qs
        table = self.table(queryset, user=request.user)
        RequestConfig(request,
                      paginate={
                          "paginator_class": EnhancedPaginator,
                          "per_page": get_paginate_count(request)
                      }).configure(table)

        return render(
            request,
            "nautobot/home.html",
            {
                "commands": registry,
                "table": table,
                "table_config_form": TableConfigForm(table)
            },
        )
Esempio n. 3
0
    def get(self, request):
        plugins = [apps.get_app_config(plugin) for plugin in settings.PLUGINS]
        data = []
        for plugin in plugins:
            data.append({
                "name": plugin.verbose_name,
                "package_name": plugin.name,
                "author": plugin.author,
                "author_email": plugin.author_email,
                "description": plugin.description,
                "version": plugin.version,
                "actions": {
                    "home": plugin.home_view_name,
                    "configure": plugin.config_view_name,
                },
            })
        table = self.table(data, user=request.user)

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(table)

        return render(
            request,
            "extras/plugins_list.html",
            {
                "table": table,
                "table_config_form": TableConfigForm(table=table),
                "filter_form": None,
            },
        )
Esempio n. 4
0
 def test_get_paginate_count_request_params(self):
     """Get the paginate count from the request's GET params, overriding user and global default values."""
     self.user.set_config("pagination.per_page", 200, commit=True)
     request = self.request_factory.get("some_paginated_view",
                                        {"per_page": 400})
     request.user = self.user
     self.assertEqual(get_paginate_count(request), 400)
Esempio n. 5
0
    def get_extra_context(self, request, instance):
        interfaces = instance.get_vminterfaces().prefetch_related("virtual_machine")
        members_table = tables.VLANVirtualMachinesTable(interfaces)

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(members_table)

        return {
            "members_table": members_table,
            "active_tab": "vminterfaces",
        }
Esempio n. 6
0
    def get_extra_context(self, request, instance):
        tagged_items = TaggedItem.objects.filter(tag=instance).prefetch_related("content_type", "content_object")

        # Generate a table of all items tagged with this Tag
        items_table = tables.TaggedItemTable(tagged_items)
        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(items_table)

        return {
            "items_count": tagged_items.count(),
            "items_table": items_table,
        }
Esempio n. 7
0
    def get_extra_context(self, request, instance):

        # Aggregates
        aggregates = Aggregate.objects.restrict(request.user, "view").filter(rir=instance).prefetch_related("tenant")

        aggregate_table = tables.AggregateTable(aggregates)

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(aggregate_table)

        return {
            "aggregate_table": aggregate_table,
        }
Esempio n. 8
0
    def get(self, request, model, **kwargs):

        # Handle QuerySet restriction of parent object if needed
        if hasattr(model.objects, "restrict"):
            obj = get_object_or_404(model.objects.restrict(request.user, "view"), **kwargs)
        else:
            obj = get_object_or_404(model, **kwargs)

        # Gather all changes for this object (and its related objects)
        content_type = ContentType.objects.get_for_model(model)
        objectchanges = (
            ObjectChange.objects.restrict(request.user, "view")
            .prefetch_related("user", "changed_object_type")
            .filter(
                Q(changed_object_type=content_type, changed_object_id=obj.pk)
                | Q(related_object_type=content_type, related_object_id=obj.pk)
            )
        )
        objectchanges_table = tables.ObjectChangeTable(data=objectchanges, orderable=False)

        # Apply the request context
        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(objectchanges_table)

        # Default to using "<app>/<model>.html" as the template, if it exists. Otherwise,
        # fall back to using base.html.
        if self.base_template is None:
            self.base_template = f"{model._meta.app_label}/{model._meta.model_name}.html"
            # TODO: This can be removed once an object view has been established for every model.
            try:
                template.loader.get_template(self.base_template)
            except template.TemplateDoesNotExist:
                self.base_template = "base.html"

        return render(
            request,
            "extras/object_changelog.html",
            {
                "object": obj,
                "table": objectchanges_table,
                "base_template": self.base_template,
                "active_tab": "changelog",
            },
        )
Esempio n. 9
0
    def get_extra_context(self, request, instance):
        # Parent prefixes table
        parent_prefixes = (Prefix.objects.restrict(
            request.user,
            "view").filter(vrf=instance.vrf,
                           prefix__net_contains=str(
                               instance.address.ip)).prefetch_related(
                                   "site", "status", "role"))
        parent_prefixes_table = tables.PrefixTable(list(parent_prefixes),
                                                   orderable=False)
        parent_prefixes_table.exclude = ("vrf", )

        # Duplicate IPs table
        duplicate_ips = (IPAddress.objects.restrict(
            request.user,
            "view").filter(vrf=instance.vrf,
                           address=str(instance.address)).exclude(
                               pk=instance.pk).prefetch_related("nat_inside"))
        # Exclude anycast IPs if this IP is anycast
        if instance.role == IPAddressRoleChoices.ROLE_ANYCAST:
            duplicate_ips = duplicate_ips.exclude(
                role=IPAddressRoleChoices.ROLE_ANYCAST)
        # Limit to a maximum of 10 duplicates displayed here
        duplicate_ips_table = tables.IPAddressTable(duplicate_ips[:10],
                                                    orderable=False)

        # Related IP table
        related_ips = (IPAddress.objects.restrict(
            request.user,
            "view").exclude(address=str(instance.address)).filter(
                vrf=instance.vrf,
                address__net_contained_or_equal=str(instance.address)))
        related_ips_table = tables.IPAddressTable(related_ips, orderable=False)

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(related_ips_table)

        return {
            "parent_prefixes_table": parent_prefixes_table,
            "duplicate_ips_table": duplicate_ips_table,
            "more_duplicate_ips": duplicate_ips.count() > 10,
            "related_ips_table": related_ips_table,
        }
Esempio n. 10
0
    def get_extra_context(self, request, instance):
        circuits = (Circuit.objects.restrict(
            request.user, "view").filter(provider=instance).prefetch_related(
                "type", "tenant", "terminations__site").annotate_sites())

        circuits_table = tables.CircuitTable(circuits)
        circuits_table.columns.hide("provider")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(circuits_table)

        return {
            "circuits_table": circuits_table,
        }
Esempio n. 11
0
    def get_extra_context(self, request, instance):

        # Prefixes
        prefixes = (
            Prefix.objects.restrict(request.user, "view")
            .filter(role=instance)
            .prefetch_related(
                "site",
                "status",
                "tenant",
                "vlan",
                "vrf",
            )
        )

        prefix_table = tables.PrefixTable(prefixes)
        prefix_table.columns.hide("role")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(prefix_table)

        # VLANs
        vlans = (
            VLAN.objects.restrict(request.user, "view")
            .filter(role=instance)
            .prefetch_related(
                "group",
                "site",
                "status",
                "tenant",
            )
        )

        vlan_table = tables.VLANTable(vlans)
        vlan_table.columns.hide("role")

        RequestConfig(request, paginate).configure(vlan_table)

        return {
            "prefix_table": prefix_table,
            "vlan_table": vlan_table,
        }
Esempio n. 12
0
    def get_extra_context(self, request, instance):

        # Clusters
        clusters = (Cluster.objects.restrict(request.user, "view").filter(
            group=instance).prefetch_related("type", "site", "tenant"))

        cluster_table = tables.ClusterTable(clusters)
        cluster_table.columns.hide("group")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(cluster_table)

        return {
            "cluster_table": cluster_table,
        }
Esempio n. 13
0
    def get_extra_context(self, request, instance):

        # Tenants
        tenants = Tenant.objects.restrict(request.user, "view").filter(
            group__in=instance.get_descendants(include_self=True))

        tenant_table = tables.TenantTable(tenants)
        tenant_table.columns.hide("group")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(tenant_table)

        return {
            "tenant_table": tenant_table,
        }
Esempio n. 14
0
    def get_extra_context(self, request, instance):
        # Find all IPAddresses belonging to this Prefix
        ipaddresses = (instance.get_child_ips().restrict(
            request.user, "view").prefetch_related("vrf", "primary_ip4_for",
                                                   "primary_ip6_for",
                                                   "status"))

        # Add available IP addresses to the table if requested
        if request.GET.get("show_available", "true") == "true":
            ipaddresses = add_available_ipaddresses(instance.prefix,
                                                    ipaddresses,
                                                    instance.is_pool)

        ip_table = tables.IPAddressTable(ipaddresses)
        if request.user.has_perm(
                "ipam.change_ipaddress") or request.user.has_perm(
                    "ipam.delete_ipaddress"):
            ip_table.columns.show("pk")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(ip_table)

        # Compile permissions list for rendering the object table
        permissions = {
            "add": request.user.has_perm("ipam.add_ipaddress"),
            "change": request.user.has_perm("ipam.change_ipaddress"),
            "delete": request.user.has_perm("ipam.delete_ipaddress"),
        }

        bulk_querystring = "vrf_id={}&parent={}".format(
            instance.vrf.pk if instance.vrf else "0", instance.prefix)

        return {
            "first_available_ip": instance.get_first_available_ip(),
            "ip_table": ip_table,
            "permissions": permissions,
            "bulk_querystring": bulk_querystring,
            "active_tab": "ip-addresses",
            "show_available": request.GET.get("show_available",
                                              "true") == "true",
        }
Esempio n. 15
0
    def get_extra_context(self, request, instance):
        # Child prefixes table
        child_prefixes = (instance.get_child_prefixes().restrict(
            request.user, "view").prefetch_related("site", "status", "role",
                                                   "vlan").annotate_tree())

        # Add available prefixes to the table if requested
        if child_prefixes and request.GET.get("show_available",
                                              "true") == "true":
            child_prefixes = add_available_prefixes(instance.prefix,
                                                    child_prefixes)

        prefix_table = tables.PrefixDetailTable(child_prefixes)
        if request.user.has_perm(
                "ipam.change_prefix") or request.user.has_perm(
                    "ipam.delete_prefix"):
            prefix_table.columns.show("pk")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(prefix_table)

        # Compile permissions list for rendering the object table
        permissions = {
            "add": request.user.has_perm("ipam.add_prefix"),
            "change": request.user.has_perm("ipam.change_prefix"),
            "delete": request.user.has_perm("ipam.delete_prefix"),
        }

        bulk_querystring = "vrf_id={}&within={}".format(
            instance.vrf.pk if instance.vrf else "0", instance.prefix)

        return {
            "first_available_prefix": instance.get_first_available_prefix(),
            "prefix_table": prefix_table,
            "permissions": permissions,
            "bulk_querystring": bulk_querystring,
            "active_tab": "prefixes",
            "show_available": request.GET.get("show_available",
                                              "true") == "true",
        }
Esempio n. 16
0
    def get_extra_context(self, request, instance):
        # Find all child prefixes contained by this aggregate
        child_prefixes = (Prefix.objects.restrict(
            request.user,
            "view").net_contained_or_equal(instance.prefix).prefetch_related(
                "site", "role").order_by("network").annotate_tree())

        # Add available prefixes to the table if requested
        if request.GET.get("show_available", "true") == "true":
            child_prefixes = add_available_prefixes(instance.prefix,
                                                    child_prefixes)

        prefix_table = tables.PrefixDetailTable(child_prefixes)
        if request.user.has_perm(
                "ipam.change_prefix") or request.user.has_perm(
                    "ipam.delete_prefix"):
            prefix_table.columns.show("pk")

        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(prefix_table)

        # Compile permissions list for rendering the object table
        permissions = {
            "add": request.user.has_perm("ipam.add_prefix"),
            "change": request.user.has_perm("ipam.change_prefix"),
            "delete": request.user.has_perm("ipam.delete_prefix"),
        }

        return {
            "prefix_table": prefix_table,
            "permissions": permissions,
            "show_available": request.GET.get("show_available",
                                              "true") == "true",
        }
Esempio n. 17
0
 def test_get_paginate_count_user_config(self):
     """Get the user's configured paginate count, overriding global defaults."""
     self.user.set_config("pagination.per_page", 200, commit=True)
     self.assertEqual(get_paginate_count(self.request), 200)
Esempio n. 18
0
 def test_get_paginate_count_settings(self):
     """Get the default paginate count from Django settings, overriding Constance config."""
     self.assertEqual(get_paginate_count(self.request), 50)
Esempio n. 19
0
 def test_get_paginate_count_config(self):
     """Get the default paginate count from Constance config."""
     self.assertEqual(get_paginate_count(self.request), 100)
Esempio n. 20
0
    def get_extra_context(self, request, instance):
        """
        Reuse the model tables for config context, device, and virtual machine but inject
        the `ConfigContextSchemaValidationStateColumn` and an object edit action button.
        """
        # Prep the validator with the schema so it can be reused for all records
        validator = Draft7Validator(instance.data_schema)

        # Config context table
        config_context_table = tables.ConfigContextTable(
            data=instance.configcontext_set.all(),
            orderable=False,
            extra_columns=[
                (
                    "validation_state",
                    tables.ConfigContextSchemaValidationStateColumn(validator, "data", empty_values=()),
                ),
                ("actions", ButtonsColumn(model=ConfigContext, buttons=["edit"])),
            ],
        )
        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(config_context_table)

        # Device table
        device_table = DeviceTable(
            data=instance.device_set.prefetch_related(
                "tenant", "site", "rack", "device_type", "device_role", "primary_ip"
            ),
            orderable=False,
            extra_columns=[
                (
                    "validation_state",
                    tables.ConfigContextSchemaValidationStateColumn(validator, "local_context_data", empty_values=()),
                ),
                ("actions", ButtonsColumn(model=Device, buttons=["edit"])),
            ],
        )
        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(device_table)

        # Virtual machine table
        virtual_machine_table = VirtualMachineTable(
            data=instance.virtualmachine_set.prefetch_related("cluster", "role", "tenant", "primary_ip"),
            orderable=False,
            extra_columns=[
                (
                    "validation_state",
                    tables.ConfigContextSchemaValidationStateColumn(validator, "local_context_data", empty_values=()),
                ),
                ("actions", ButtonsColumn(model=VirtualMachine, buttons=["edit"])),
            ],
        )
        paginate = {
            "paginator_class": EnhancedPaginator,
            "per_page": get_paginate_count(request),
        }
        RequestConfig(request, paginate).configure(virtual_machine_table)

        return {
            "config_context_table": config_context_table,
            "device_table": device_table,
            "virtual_machine_table": virtual_machine_table,
            "active_tab": "validation",
        }