Add filter form to the context.

        TODO: Currently we construct the filter form object twice - in
        get_queryset and here, in get_context_data. Will need to figure out a
        good way to eliminate extra initialization.
978478
def get_context_data(self, **kwargs):
        
        context = super(FilterFormMixin, self).get_context_data(**kwargs)
        context[self.context_filterform_name] = self.get_filter()
        return context
107591
private function applyFilters()
    {
        // Manage filters
        // Filter values come either from the form (GET)
        // Or from session
        $form = $this->getFiltersForm();

        if (!$form) {
            // No filters are configured for this admin
            return;
        }

        $this->loadFilterValues();
        // Init form with current data if any
        $form->setData($this->filterValues);

        $form->handleRequest($this->request);

        if ($form->isSubmitted()) {

            if ($form->get('reset')->isClicked()) {
                // Submitted for reset
                // Reset stored content
                $this->clearFilterValues();
                // Reset displayed values by rebuilding the form
                // yes, it's a pity we cannot simply change content of it
                $this->getFiltersForm(true);
            }
            else {
                // Submitted for filtering
                // Overwrite any stored values with the submitted ones
                // Update storage for subsequent requests
                $this->storeFilterValues($form->getData());
            }
        }

        // Map values, if any, to filters
        if (is_array($this->filterValues)) {
            foreach ($this->filters as $filter) {
                if (array_key_exists($filter->getName(), $this->filterValues)) {
                    $filter->setValue($this->filterValues[$filter->getName()]);
                }
            }
        }
    }
837384
def get_queryset(self):
        
        self.init_preferences()
        queryset = super(PreferenceViewSet, self).get_queryset()

        section = self.request.query_params.get('section')
        if section:
            queryset = queryset.filter(section=section)

        return queryset
703267
def _fill_form_exclude_cols(self, exclude_cols, form):
        
        for filter_key in exclude_cols:
            filter_value = self._filters.get_filter_value(filter_key)
            rel_obj = self.datamodel.get_related_obj(filter_key, filter_value)
            if hasattr(form, filter_key):
                field = getattr(form, filter_key)
                field.data = rel_obj
13433
def initialize_context(self, request: HttpRequest, *args, **kwargs) -> None:
        
        for key in self.CONTEXT_KEYS:
            setattr(self, key, kwargs.get(key))
        for key in self.QUERY_CONTEXT_KEYS:
            setattr(self, key, request.query_params.get(key))
        self._initialize_context()
        self.validate_context()
515244
def filter_queryset(self, request, queryset, view):
        
        self.request = request
        self.view = view

        # enable addition of extra filters (i.e., a Q())
        # so custom filters can be added to the queryset without
        # running into https://code.djangoproject.com/ticket/18437
        # which, without this, would mean that filters added to the queryset
        # after this is called may not behave as expected
        extra_filters = self.view.get_extra_filters(request)

        disable_prefetches = self.view.is_update()

        self.DEBUG = settings.DEBUG

        return self._build_queryset(
            queryset=queryset,
            extra_filters=extra_filters,
            disable_prefetches=disable_prefetches,
        )
650349
def get_context_data(self, **kwargs):
        
        #noinspection PyUnresolvedReferences
        query_str           = self.request.GET.get('q', None)
        queryset            = kwargs.pop('object_list', self.object_list)
        context_object_name = self.get_context_object_name(queryset)

        # Build the context dictionary.
        context = {
            'ordering':     self.get_ordering(),
            'query_string': query_str,
            'is_searching': bool(query_str),
        }

        # Add extra variables to context for non-AJAX requests.
        #noinspection PyUnresolvedReferences
        if not self.request.is_ajax() or kwargs.get('force_search', False):
            context.update({
                'search_form':  self.get_search_form(),
                'popular_tags': self.model.popular_tags()
            })

        if context_object_name is not None:
            context[context_object_name] = queryset

        # Update context with any additional keyword arguments.
        context.update(kwargs)

        return super(IndexView, self).get_context_data(**context)
588838
def get_filterset_kwargs(self, request, queryset, view):
        
        filter_keys = []
        # rewrite filter[field] query params to make DjangoFilterBackend work.
        data = request.query_params.copy()
        for qp, val in request.query_params.items():
            m = self.filter_regex.match(qp)
            if m and (not m.groupdict()['assoc'] or
                      m.groupdict()['ldelim'] != '[' or m.groupdict()['rdelim'] != ']'):
                raise ValidationError("invalid query parameter: {}".format(qp))
            if m and qp != self.search_param:
                if not val:
                    raise ValidationError("missing {} test value".format(qp))
                # convert jsonapi relationship path to Django ORM's __ notation
                key = m.groupdict()['assoc'].replace('.', '__')
                # undo JSON_API_FORMAT_FIELD_NAMES conversion:
                key = format_value(key, 'underscore')
                data[key] = val
                filter_keys.append(key)
                del data[qp]
        return {
            'data': data,
            'queryset': queryset,
            'request': request,
            'filter_keys': filter_keys,
        }
165918
public static function add_filter_to_form(\MoodleQuickForm &$mform) {
        $options = ['multiple' => true];

        $filtername = self::get_filter_name();
        $key = "filter_{$filtername}";

        $mform->addElement('course', $key, get_string($key, 'tool_usertours'), $options);
        $mform->setDefault($key, '0');
        $mform->addHelpButton($key, $key, 'tool_usertours');
    }
667273
def comment_form(context, object):
    
    user = context.get("user")
    form_class = context.get("form", CommentForm)
    form = form_class(obj=object, user=user)
    return form
983023
private function addFilters()
    {
        foreach ($this->_data as $requestName => $requestConfig) {
            if (isset($requestConfig['filters'])) {
                $filters = [];

                foreach ($requestConfig['filters'] as $filterName => $filterClass) {
                    $filters[$filterName] = $this->objectManager->get($filterClass);
                }

                $this->_data[$requestName]['filters'] = $filters;
            }
        }
    }
1054826
def get_context_data(self, **kwargs):
        
        for key in self.get_form_class_keys():
            kwargs['{}_form'.format(key)] = self.get_form(key)
        return super(FormMixin, self).get_context_data(**kwargs)
270799
def get_filterset(self, request, queryset, view):
        
        # TODO: .base_filters vs. .filters attr (not always present)
        filterset_class = self.get_filterset_class(view, queryset)
        kwargs = self.get_filterset_kwargs(request, queryset, view)
        self._validate_filter(kwargs.pop('filter_keys'), filterset_class)
        if filterset_class is None:
            return None
        return filterset_class(**kwargs)
244025
def filter(self, field_name, field_value):
        
        self.filters.append((field_name, field_value))
        return self
1294359
def filter(self, **kwargs):
        
        readFilter = ReadFilter(**kwargs)
        self._filters.append(readFilter.filter)
        return self
894007
def get(self, request, *args, **kwargs):
        
        #noinspection PyAttributeOutsideInit
        self.object_list    = self.get_queryset()
        context             = self.get_context_data(force_search=True)

        if self.form_class:
            context.update({'form': self.get_form()})

        if 'q' in request.GET or 'p' in request.GET:
            return render(
                request,
                '{0}/results.html'.format(self.template_dir),
                context
            )
        else:
            return render_modal_workflow(
                request,
                '{0}/chooser.html'.format(self.template_dir),
                '{0}/chooser.js'.format(self.template_dir),
                context
            )
353
def filtered_context(context):
    """"""

    ctx = Context(context.opt)
    for resource in context.resources():
        if resource.child:
            continue

        if resource.filtered():
            ctx.add(resource)

    return ctx