コード例 #1
0
ファイル: views.py プロジェクト: sky365365/netbox
    def post(self, request):

        # Update the user's table configuration
        table = self.table(self.queryset)
        form = TableConfigForm(table=table, data=request.POST)
        preference_name = f"tables.{self.table.__name__}.columns"

        if form.is_valid():
            if 'set' in request.POST:
                request.user.config.set(preference_name,
                                        form.cleaned_data['columns'],
                                        commit=True)
            elif 'clear' in request.POST:
                request.user.config.clear(preference_name, commit=True)
            messages.success(request, "Your preferences have been updated.")

        return redirect(request.get_full_path())
コード例 #2
0
ファイル: helpers.py プロジェクト: fdomain/netbox
def table_config_form(table, table_name=None):
    return {
        'table_name': table_name or table.__class__.__name__,
        'form': TableConfigForm(table=table),
    }
コード例 #3
0
ファイル: views.py プロジェクト: sky365365/netbox
    def get(self, request):

        model = self.queryset.model
        content_type = ContentType.objects.get_for_model(model)

        if self.filterset:
            self.queryset = self.filterset(request.GET, self.queryset).qs

        # If this type of object has one or more custom fields, prefetch any relevant custom field values
        custom_fields = CustomField.objects.filter(
            obj_type=ContentType.objects.get_for_model(
                model)).prefetch_related('choices')
        if custom_fields:
            self.queryset = self.queryset.prefetch_related(
                'custom_field_values')

        # Check for export template rendering
        if request.GET.get('export'):
            et = get_object_or_404(ExportTemplate,
                                   content_type=content_type,
                                   name=request.GET.get('export'))
            queryset = CustomFieldQueryset(
                self.queryset,
                custom_fields) if custom_fields else self.queryset
            try:
                return et.render_to_response(queryset)
            except Exception as e:
                messages.error(
                    request,
                    "There was an error rendering the selected export template ({}): {}"
                    .format(et.name, e))

        # Check for YAML export support
        elif 'export' in request.GET and hasattr(model, 'to_yaml'):
            response = HttpResponse(self.queryset_to_yaml(),
                                    content_type='text/yaml')
            filename = 'netbox_{}.yaml'.format(
                self.queryset.model._meta.verbose_name_plural)
            response[
                'Content-Disposition'] = 'attachment; filename="{}"'.format(
                    filename)
            return response

        # Fall back to built-in CSV formatting if export requested but no template specified
        elif 'export' in request.GET and hasattr(model, 'to_csv'):
            response = HttpResponse(self.queryset_to_csv(),
                                    content_type='text/csv')
            filename = 'netbox_{}.csv'.format(
                self.queryset.model._meta.verbose_name_plural)
            response[
                'Content-Disposition'] = 'attachment; filename="{}"'.format(
                    filename)
            return response

        # Provide a hook to tweak the queryset based on the request immediately prior to rendering the object list
        self.queryset = self.alter_queryset(request)

        # Compile a dictionary indicating which permissions are available to the current user for this model
        permissions = {}
        for action in ('add', 'change', 'delete', 'view'):
            perm_name = '{}.{}_{}'.format(model._meta.app_label, action,
                                          model._meta.model_name)
            permissions[action] = request.user.has_perm(perm_name)

        # Construct the table based on the user's permissions
        if request.user.is_authenticated:
            columns = request.user.config.get(
                f"tables.{self.table.__name__}.columns")
        else:
            columns = None
        table = self.table(self.queryset, columns=columns)
        if 'pk' in table.base_columns and (permissions['change']
                                           or permissions['delete']):
            table.columns.show('pk')

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

        context = {
            'content_type':
            content_type,
            'table':
            table,
            'permissions':
            permissions,
            'action_buttons':
            self.action_buttons,
            'table_config_form':
            TableConfigForm(table=table),
            'filter_form':
            self.filterset_form(request.GET, label_suffix='')
            if self.filterset_form else None,
        }
        context.update(self.extra_context())

        return render(request, self.template_name, context)
コード例 #4
0
    def get(self, request):

        model = self.queryset.model
        content_type = ContentType.objects.get_for_model(model)

        if self.filterset:
            self.queryset = self.filterset(request.GET, self.queryset).qs

        # Check for export template rendering
        if request.GET.get('export'):
            et = get_object_or_404(ExportTemplate, content_type=content_type, name=request.GET.get('export'))
            try:
                return et.render_to_response(self.queryset)
            except Exception as e:
                messages.error(
                    request,
                    "There was an error rendering the selected export template ({}): {}".format(
                        et.name, e
                    )
                )

        # Check for YAML export support
        elif 'export' in request.GET and hasattr(model, 'to_yaml'):
            response = HttpResponse(self.queryset_to_yaml(), content_type='text/yaml')
            filename = 'netbox_{}.yaml'.format(self.queryset.model._meta.verbose_name_plural)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
            return response

        # Fall back to built-in CSV formatting if export requested but no template specified
        elif 'export' in request.GET and hasattr(model, 'to_csv'):
            response = HttpResponse(self.queryset_to_csv(), content_type='text/csv')
            filename = 'netbox_{}.csv'.format(self.queryset.model._meta.verbose_name_plural)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
            return response

        # Compile a dictionary indicating which permissions are available to the current user for this model
        permissions = {}
        for action in ('add', 'change', 'delete', 'view'):
            perm_name = get_permission_for_model(model, action)
            permissions[action] = request.user.has_perm(perm_name)

        # Construct the objects table
        table = self.table(self.queryset, user=request.user)
        if 'pk' in table.base_columns and (permissions['change'] or permissions['delete']):
            table.columns.show('pk')

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

        context = {
            'content_type': content_type,
            'table': table,
            'permissions': permissions,
            'action_buttons': self.action_buttons,
            'table_config_form': TableConfigForm(table=table),
            'filter_form': self.filterset_form(request.GET, label_suffix='') if self.filterset_form else None,
        }
        context.update(self.extra_context())

        return render(request, self.template_name, context)