Exemple #1
0
    def __init__(self,
                 target_models=None,
                 can_choose_root=False,
                 user_perms=None,
                 **kwargs):
        super().__init__(**kwargs)

        if target_models:
            if not isinstance(target_models, (set, list, tuple)):
                # assume we've been passed a single instance; wrap it as a list
                target_models = [target_models]

            # normalise the list of target models to a list of page classes
            cleaned_target_models = []
            for model in target_models:
                try:
                    cleaned_target_models.append(resolve_model_string(model))
                except (ValueError, LookupError):
                    raise ImproperlyConfigured(
                        "Could not resolve %r into a model. "
                        "Model names should be in the form app_label.model_name"
                        % (model, ))
        else:
            cleaned_target_models = [Page]

        if len(cleaned_target_models
               ) == 1 and cleaned_target_models[0] is not Page:
            model_name = cleaned_target_models[0]._meta.verbose_name.title()
            self.choose_one_text += " (" + model_name + ")"

        self.user_perms = user_perms
        self.target_models = cleaned_target_models
        self.can_choose_root = bool(can_choose_root)
Exemple #2
0
    def get_queryset(self):
        '''
        This is overwritten in order to not exclude drafts
        and pages submitted for moderation
        '''
        request = self.request

        # Allow pages to be filtered to a specific type
        if 'type' not in request.GET:
            model = Page
        else:
            model_name = request.GET['type']
            try:
                model = resolve_model_string(model_name)
            except LookupError:
                raise BadRequestError("type doesn't exist")
            if not issubclass(model, Page):
                raise BadRequestError("type doesn't exist")

        # This is the overwritten line
        queryset = model.objects.public()  # exclude .live()

        # Filter by site
        queryset = queryset.descendant_of(request.site.root_page,
                                          inclusive=True)

        return queryset
Exemple #3
0
 def get_calendar_events(self, start, end):
     # start with all child events, regardless of get_index_children rules.
     querymodel = resolve_model_string(self.index_query_pagemodel,
                                       self._meta.app_label)
     qs = querymodel.objects.child_of(self).live()
     event_instances = []
     for event in qs:
         occurrences = event.query_occurrences(limit=None,
                                               from_date=start,
                                               to_date=end)
         for occurrence in occurrences:
             event_data = {
                 'title':
                 event.title,
                 'start':
                 occurrence[0].strftime('%Y-%m-%dT%H:%M:%S'),
                 'end':
                 occurrence[1].strftime('%Y-%m-%dT%H:%M:%S')
                 if occurrence[1] else "",
                 'description':
                 "",
             }
             if event.url:
                 event_data['url'] = event.url
             if event.calendar_color:
                 event_data['backgroundColor'] = event.calendar_color
             event_instances.append(event_data)
     return event_instances
Exemple #4
0
    def get_queryset(self):
        '''
        This is overwritten in order to not exclude drafts
        and pages submitted for moderation
        '''
        request = self.request

        # Allow pages to be filtered to a specific type
        if 'type' not in request.GET:
            model = Page
        else:
            model_name = request.GET['type']
            try:
                model = resolve_model_string(model_name)
            except LookupError:
                raise BadRequestError("type doesn't exist")
            if not issubclass(model, Page):
                raise BadRequestError("type doesn't exist")

        # This is the overwritten line
        queryset = model.objects.public()  # exclude .live()

        # Filter by site
        queryset = queryset.descendant_of(
            request.site.root_page, inclusive=True)

        return queryset
    def target_models(self):
        target_models = []

        for target_model in self.page_type:
            target_models.append(resolve_model_string(target_model))

        return target_models
Exemple #6
0
    def target_models(self):
        target_models = []

        for target_model in self.page_type:
            target_models.append(
                resolve_model_string(target_model)
            )

        return target_models
Exemple #7
0
    def get_index_children(self):
        """
        Override to return query of subpages as defined by `index_` variables.
        """
        if self.index_query_pagemodel and self.index_order_by:
            querymodel = resolve_model_string(self.index_query_pagemodel, self._meta.app_label)
            return querymodel.objects.child_of(self).live().order_by(self.index_order_by)

        return super().get_children().live()
Exemple #8
0
    def target_model(self):
        """
        Defines the model used by the base ChooserBlock for ID <-> instance
        conversions. If a single page type is specified in target_model,
        we can use that to get the more specific instance "for free"; otherwise
        use the generic Page model.
        """
        if len(self.target_models) == 1:
            return self.target_models[0]

        return resolve_model_string('wagtailcore.Page')
Exemple #9
0
    def target_model(self):
        """
        Defines the model used by the base ChooserBlock for ID <-> instance
        conversions. If a single page type is specified in target_model,
        we can use that to get the more specific instance "for free"; otherwise
        use the generic Page model.
        """
        if len(self.target_models) == 1:
            return self.target_models[0]

        return resolve_model_string('wagtailcore.Page')
Exemple #10
0
def page_models_from_string(string):
    page_models = []

    for sub_string in string.split(','):
        page_model = resolve_model_string(sub_string)

        if not issubclass(page_model, Page):
            raise ValueError("Model is not a page")

        page_models.append(page_model)

    return tuple(page_models)
def page_models_from_string(string):
    page_models = []

    for sub_string in string.split(','):
        page_model = resolve_model_string(sub_string)

        if not issubclass(page_model, Page):
            raise ValueError("Model is not a page")

        page_models.append(page_model)

    return tuple(page_models)
Exemple #12
0
    def get_index_children(self):
        if self.index_query_pagemodel and self.index_order_by == 'next_occurrence':
            querymodel = resolve_model_string(self.index_query_pagemodel, self._meta.app_label)
            qs = querymodel.objects.child_of(self).live()
            # filter out events that don't have a next_occurrence
            upcoming = []
            for event in qs.all():
                if event.next_occurrence():
                    upcoming.append(event)
            # sort the events by next_occurrence
            return sorted(upcoming, key=lambda e: e.next_occurrence())

        return super().get_index_children()
Exemple #13
0
    def get_create_model(self):
        """
        To be called after dispatch(); returns the model to use for a new task if one is known
        (either from being the only available task mode, or from being specified in the URL as create_model)
        """
        if self.can_create:
            if len(self.task_models) == 1:
                return self.task_models[0]

            elif 'create_model' in self.request.GET:
                create_model = resolve_model_string(
                    self.request.GET['create_model'])

                if create_model not in self.task_models:
                    raise Http404

                return create_model
Exemple #14
0
 def target_model(self):
     if self._target_model:
         try:
             return resolve_model_string(self._target_model)
         except LookupError:
             raise ImproperlyConfigured(
                 "{0}.target_model must be of the form 'app_label.model_name', "
                 "given {1!r}".format(
                     self.__class__.__name__, self._target_model
                 )
             )
         except ValueError:
             raise ImproperlyConfigured(
                 "{0}.target_model refers to model {1!r} that has not been installed".format(
                     self.__class__.__name__, self._target_model
                 )
             )
     return self.db_field.remote_field.model
Exemple #15
0
    def target_models(self):
        if self.page_type:
            target_models = []

            for page_type in self.page_type:
                try:
                    target_models.append(resolve_model_string(page_type))
                except LookupError:
                    raise ImproperlyConfigured(
                        "{0}.page_type must be of the form 'app_label.model_name', given {1!r}"
                        .format(self.__class__.__name__, page_type))
                except ValueError:
                    raise ImproperlyConfigured(
                        "{0}.page_type refers to model {1!r} that has not been installed"
                        .format(self.__class__.__name__, page_type))

            return target_models
        return [self.db_field.remote_field.model]
Exemple #16
0
    def target_models(cls):
        if cls.page_type:
            target_models = []

            for page_type in cls.page_type:
                try:
                    target_models.append(resolve_model_string(page_type))
                except LookupError:
                    raise ImproperlyConfigured(
                        "{0}.page_type must be of the form 'app_label.model_name', given {1!r}"
                        .format(cls.__name__, page_type))
                except ValueError:
                    raise ImproperlyConfigured(
                        "{0}.page_type refers to model {1!r} that has not been installed"
                        .format(cls.__name__, page_type))

            return target_models
        else:
            return [
                cls.model._meta.get_field(cls.field_name).remote_field.model
            ]
Exemple #17
0
    def target_models(self):
        if self.page_type:
            target_models = []

            for page_type in self.page_type:
                try:
                    target_models.append(resolve_model_string(page_type))
                except LookupError:
                    raise ImproperlyConfigured(
                        "{0}.page_type must be of the form 'app_label.model_name', given {1!r}".format(
                            self.__class__.__name__, page_type
                        )
                    )
                except ValueError:
                    raise ImproperlyConfigured(
                        "{0}.page_type refers to model {1!r} that has not been installed".format(
                            self.__class__.__name__, page_type
                        )
                    )

            return target_models
        return [self.db_field.remote_field.model]
    def get_queryset(self):
        '''
        This is overwritten in order to not exclude drafts
        and pages submitted for moderation
        '''
        request = self.request

        # Allow pages to be filtered to a specific type
        if 'type' not in request.GET:
            model = Page
        else:
            model_name = request.GET['type']
            try:
                model = resolve_model_string(model_name)
            except LookupError:
                raise BadRequestError("type doesn't exist")
            if not issubclass(model, Page):
                raise BadRequestError("type doesn't exist")

        # This is the overwritten line
        queryset = model.objects.public()  # exclude .live()

        # Filter by site
        queryset = queryset.descendant_of(request.site.root_page,
                                          inclusive=True)

        # Enable filtering by navigation tags
        if model == ArticlePage and 'nav_tags__tag' in request.GET:
            try:
                queryset = queryset.filter(
                    nav_tags__tag=request.GET['nav_tags__tag'])
            except ValueError as e:
                raise BadRequestError(
                    "field filter error. '%s' is not a valid value "
                    "for nav_tags__tag (%s)" %
                    (request.GET['nav_tags__tag'], str(e)))

        return queryset
    def get_queryset(self):
        request = self.request

        # Allow pages to be filtered to a specific type
        if 'type' not in request.GET:
            model = Page
        else:
            model_name = request.GET['type']
            try:
                model = resolve_model_string(model_name)
            except LookupError:
                raise BadRequestError("type doesn't exist")
            if not issubclass(model, Page):
                raise BadRequestError("type doesn't exist")

        # Get live pages that are not in a private section
        queryset = model.objects.public().live()

        # Filter by site
        queryset = queryset.descendant_of(request.site.root_page,
                                          inclusive=True)

        return queryset
Exemple #20
0
    def test_resolve_from_string(self):
        model = resolve_model_string('wagtailcore.Page')

        self.assertEqual(model, Page)
Exemple #21
0
 def target_model(self):
     return resolve_model_string(self._target_model)
 def target_model(self):
     if isinstance(self._target_model, str):
         return resolve_model_string(self._target_model)
     return self._target_model
Exemple #23
0
 def target_model(self):
     return resolve_model_string('coderedcms.ClassifierTerm')
Exemple #24
0
def task_chooser(request):
    task_models = get_task_types()
    create_model = None
    can_create = False

    if task_permission_policy.user_has_permission(request.user, 'add'):
        can_create = len(task_models) != 0

        if len(task_models) == 1:
            create_model = task_models[0]

        elif 'create_model' in request.GET:
            create_model = resolve_model_string(request.GET['create_model'])

            if create_model not in task_models:
                raise Http404

    # Build task types list for "select task type" view
    task_types = [
        (model.get_verbose_name(), model._meta.app_label, model._meta.model_name, model.get_description())
        for model in task_models
    ]
    # sort by lower-cased version of verbose name
    task_types.sort(key=lambda task_type: task_type[0].lower())

    # Build task type choices for filter on "existing task" tab
    task_type_choices = [
        (model, model.get_verbose_name())
        for model in task_models
    ]
    task_type_choices.sort(key=lambda task_type: task_type[1].lower())

    if create_model:
        createform_class = get_task_form_class(create_model)
    else:
        createform_class = None

    q = None
    if 'q' in request.GET or 'p' in request.GET or 'task_type' in request.GET:
        searchform = TaskChooserSearchForm(request.GET, task_type_choices=task_type_choices)
        tasks = all_tasks = searchform.task_model.objects.order_by(Lower('name'))
        q = ''

        if searchform.is_searching():
            # Note: I decided not to use wagtailsearch here. This is because
            # wagtailsearch creates a new index for each model you make
            # searchable and this might affect someone's quota. I doubt there
            # would ever be enough tasks to require using anything more than
            # an icontains anyway.
            q = searchform.cleaned_data['q']
            tasks = tasks.filter(name__icontains=q)

        # Pagination
        paginator = Paginator(tasks, per_page=10)
        tasks = paginator.get_page(request.GET.get('p'))

        return TemplateResponse(request, "wagtailadmin/workflows/task_chooser/includes/results.html", {
            'task_types': task_types,
            'searchform': searchform,
            'tasks': tasks,
            'all_tasks': all_tasks,
            'query_string': q,
        })
    else:
        if createform_class:
            if request.method == 'POST':
                createform = createform_class(request.POST, request.FILES, prefix='create-task')

                if createform.is_valid():
                    task = createform.save()

                    response = render_modal_workflow(
                        request, None, None,
                        None, json_data={'step': 'task_chosen', 'result': get_task_result_data(task)}
                    )

                    # Use a different status code so we can tell the difference between validation errors and successful creations
                    response.status_code = 201

                    return response
            else:
                createform = createform_class(prefix='create-task')
        else:
            if request.method == 'POST':
                return HttpResponseBadRequest()

            createform = None

        searchform = TaskChooserSearchForm(task_type_choices=task_type_choices)
        tasks = searchform.task_model.objects.order_by(Lower('name'))

        paginator = Paginator(tasks, per_page=10)
        tasks = paginator.get_page(request.GET.get('p'))

        return render_modal_workflow(request, 'wagtailadmin/workflows/task_chooser/chooser.html', None, {
            'task_types': task_types,
            'tasks': tasks,
            'searchform': searchform,
            'createform': createform,
            'can_create': can_create,
            'add_url': reverse('wagtailadmin_workflows:task_chooser') + '?' + request.GET.urlencode() if create_model else None
        }, json_data=get_chooser_context())
Exemple #25
0
    def test_resolve_from_class(self):
        model = resolve_model_string(Page)

        self.assertEqual(model, Page)
Exemple #26
0
    def test_resolve_from_string_with_default_app(self):
        model = resolve_model_string('Page', default_app='wagtailcore')

        self.assertEqual(model, Page)
Exemple #27
0
    def test_resolve_from_string_with_different_default_app(self):
        model = resolve_model_string("wagtailcore.Page",
                                     default_app="wagtailadmin")

        self.assertEqual(model, Page)
Exemple #28
0
    def test_resolve_from_string(self):
        model = resolve_model_string("wagtailcore.Page")

        self.assertEqual(model, Page)
Exemple #29
0
    def get_post_model(cls):
        if not cls.post_model:
            return

        return resolve_model_string(cls.post_model)
Exemple #30
0
    def test_resolve_from_class(self):
        model = resolve_model_string(Page)

        self.assertEqual(model, Page)
Exemple #31
0
    def test_resolve_from_string_with_different_default_app(self):
        model = resolve_model_string('wagtailcore.Page', default_app='wagtailadmin')

        self.assertEqual(model, Page)
Exemple #32
0
 def target_model(self):
     return resolve_model_string(self._target_model)
Exemple #33
0
 def get_newsitem_model(cls):
     return resolve_model_string(cls.newsitem_model, cls._meta.app_label)