Python django.contrib.contenttypes.models.ContentType.DoesNotExist() Examples

The following are 22 code examples of django.contrib.contenttypes.models.ContentType.DoesNotExist(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.contenttypes.models.ContentType , or try the search function .
Example #1
Source File: tasks.py    From FIR with GNU General Public License v3.0 6 votes vote down vote up
def handle_notification(content_type, instance, business_lines, event):
    from fir_notifications.registry import registry
    from django.contrib.contenttypes.models import ContentType
    try:
        model = ContentType.objects.get_for_id(content_type).model_class()
    except ContentType.DoesNotExist:
        print("Unknown content type")
        return
    try:
        instance = model.objects.get(id=instance)
    except model.DoesNotExist:
        print("Unknown instance")
        return
    users = get_user_templates(event, business_lines)
    for method in registry.get_methods():
        method.send(event, users, instance, business_lines) 
Example #2
Source File: models.py    From FIR with GNU General Public License v3.0 6 votes vote down vote up
def update_relations(self, source_instance, data):
        relations = []
        src_ct = ContentType.objects.get_for_model(source_instance)
        for model, link in registry.model_links.items():
            parser, url, reverse = link
            tgt_ct = None
            for match in parser.finditer(data):
                if match:
                    if tgt_ct is None:
                        try:
                            tgt_ct = ContentType.objects.get_by_natural_key(*model.lower().split('.'))
                        except ContentType.DoesNotExist:
                            continue
                    relation, created = self.get_or_create(
                        src_content_type=src_ct,
                        src_object_id=source_instance.pk,
                        tgt_content_type=tgt_ct,
                        tgt_object_id=match.group(1)
                    )
                    relations.append(relation)
        return relations 
Example #3
Source File: tags.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def autocomplete(request, app_name=None, model_name=None):
    if app_name and model_name:
        try:
            content_type = ContentType.objects.get_by_natural_key(app_name, model_name)
        except ContentType.DoesNotExist:
            raise Http404

        tag_model = content_type.model_class()
        if not issubclass(tag_model, TagBase):
            raise Http404

    else:
        tag_model = Tag

    term = request.GET.get('term', None)
    if term:
        tags = tag_model.objects.filter(name__istartswith=term).order_by('name')
    else:
        tags = tag_model.objects.none()

    return JsonResponse([tag.name for tag in tags], safe=False) 
Example #4
Source File: pages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def content_type_use(request, content_type_app_name, content_type_model_name):
    try:
        content_type = ContentType.objects.get_by_natural_key(content_type_app_name, content_type_model_name)
    except ContentType.DoesNotExist:
        raise Http404

    page_class = content_type.model_class()

    # page_class must be a Page type and not some other random model
    if not issubclass(page_class, Page):
        raise Http404

    pages = page_class.objects.all()

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

    return TemplateResponse(request, 'wagtailadmin/pages/content_type_use.html', {
        'pages': pages,
        'app_name': content_type_app_name,
        'content_type': content_type,
        'page_class': page_class,
    }) 
Example #5
Source File: views.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def index(request, page_pk=None):
    page_qs = HelpBasePage.objects.filter(tree_id=1)

    # either of these should result in a QuerySet with one result
    if page_pk is not None:
        page_qs = page_qs.filter(pk=page_pk)
    else:
        page_qs = page_qs.filter(parent__isnull=True)

    try:
        page = page_qs.get()
    except HelpBasePage.DoesNotExist:
        raise Http404

    context = {
        "page": page,
        "breadcrumbs": breadcrumb_iterator(page),
    }

    return TemplateResponse(
            request,
            "cms/admin/index.html",
            context,
    ) 
Example #6
Source File: views.py    From Inboxen with GNU Affero General Public License v3.0 6 votes vote down vote up
def choose_page_type(request, parent_pk):
    try:
        page = HelpBasePage.objects.get(pk=parent_pk)
    except HelpBasePage.DoesNotExist:
        raise Http404

    context = {
        "models": [model._meta for model in PAGE_TYPES],
        "parent_pk": parent_pk,
        "breadcrumbs": breadcrumb_iterator(page),
    }

    return TemplateResponse(
            request,
            "cms/admin/choose_page_type.html",
            context,
    ) 
Example #7
Source File: generics.py    From drf-haystack with MIT License 5 votes vote down vote up
def get_object(self):
        """
        Fetch a single document from the data store according to whatever
        unique identifier is available for that document in the
        SearchIndex.

        In cases where the view has multiple ``index_models``, add a ``model`` query
        parameter containing a single `app_label.model` name to the request in order
        to override which model to include in the SearchQuerySet.

        Example:
            /api/v1/search/42/?model=myapp.person
        """
        queryset = self.get_queryset()
        if "model" in self.request.query_params:
            try:
                app_label, model = map(six.text_type.lower, self.request.query_params["model"].split(".", 1))
                ctype = ContentType.objects.get(app_label=app_label, model=model)
                queryset = self.get_queryset(index_models=[ctype.model_class()])
            except (ValueError, ContentType.DoesNotExist):
                raise Http404("Could not find any models matching '%s'. Make sure to use a valid "
                              "'app_label.model' name for the 'model' query parameter." % self.request.query_params["model"])

        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        if lookup_url_kwarg not in self.kwargs:
            raise AttributeError(
                "Expected view %s to be called with a URL keyword argument "
                "named '%s'. Fix your URL conf, or set the `.lookup_field` "
                "attribute on the view correctly." % (self.__class__.__name__, lookup_url_kwarg)
            )
        queryset = queryset.filter(self.query_object((self.document_uid_field, self.kwargs[lookup_url_kwarg])))
        count = queryset.count()
        if count == 1:
            return queryset[0]
        elif count > 1:
            raise Http404("Multiple results matches the given query. Expected a single result.")

        raise Http404("No result matches the given query.") 
Example #8
Source File: models.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def model_from_activity(activity) -> Type[models.Model]:
        """ Get the specific inheriting child from the activity.

        Inverse of activity().
        """
        model = ''.join(activity.split('_')).lower() + 'leaderapplication'
        try:
            content_type = ContentType.objects.get(app_label="ws", model=model)
        except ContentType.DoesNotExist:
            raise NoApplicationDefined(f"No application for {activity}")

        model_class = content_type.model_class()
        if model_class is None:
            raise NoApplicationDefined(f"No application for {activity}")
        return model_class 
Example #9
Source File: models.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def reciprocally_paired_with(self):
        """ Return requested partner if they also requested to be paired. """
        if not (self.pk and self.paired_with):  # Must be saved & paired!
            return None

        try:
            other_paired_id = self.paired_with.lotteryinfo.paired_with_id
        except self.DoesNotExist:  # Paired participant has no lottery info
            return None

        if not other_paired_id:
            return None

        reciprocal = other_paired_id == self.participant_id
        return self.paired_with if reciprocal else None 
Example #10
Source File: models.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def _cannot_attend_because_missed_lectures(self, trip) -> bool:
        """ Return if the participant's lack of attendance should prevent their attendance.

        This method exists to allow WS leaders to attend trips as a
        participant, even if they've missed lectures this year. So long as
        they've been to a recent year's lectures, we'll allow them to sign up
        as participants (though they will still be rendered as having missed
        the current year's lectures in any UI that surfaces that information).
        """
        if not self.missed_lectures_for(trip):
            return False  # Attended this year

        # For Winter School leaders, we have a carve-out if you've attended lectures recently
        if not self.can_lead(enums.Program.WINTER_SCHOOL):
            # (All other participants must have attended this year's lectures)
            return True

        try:
            last_attendance = self.lectureattendance_set.latest('year')
        except LectureAttendance.DoesNotExist:
            return True  # First-time leaders must have attended lectures!

        # Leaders who have attended any of the last 4 years' lectures may attend trips.
        # e.g. if you attended lectures in 2016, you may attend trips in IAP of 2020, but not 2021
        years_since_last_lecture = date_utils.ws_year() - last_attendance.year
        return years_since_last_lecture > 4 
Example #11
Source File: models.py    From mitoc-trips with GNU General Public License v3.0 5 votes vote down vote up
def from_user(cls, user, join_membership=False):
        if not user.is_authenticated:
            return None

        one_or_none = cls.objects.filter(user_id=user.id)
        if join_membership:
            one_or_none = one_or_none.select_related('membership')

        try:
            return one_or_none.get()
        except cls.DoesNotExist:
            return None 
Example #12
Source File: views.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_page(request, page_pk):
    qs = HelpBasePage.objects.filter(lft=(F("rght") - 1))

    try:
        # lft - rght should be 1 if this is a leaf node
        page = qs.get(pk=page_pk).specific
    except HelpBasePage.DoesNotExist:
        raise Http404

    if request.method == "POST":
        form = DeleteForm(data=request.POST)
        if form.is_valid():
            kwargs = {}
            if page.parent_id:
                kwargs = {"page_pk": page.parent_id}

            page.delete()
            return HttpResponseRedirect(reverse("admin:index", kwargs=kwargs))
    else:
        form = DeleteForm()

    return TemplateResponse(
            request,
            "cms/admin/delete_page.html",
            {
                "form": form,
                "page": page,
                "breadcrumbs": breadcrumb_iterator(page),
            }
    ) 
Example #13
Source File: views.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def edit_page(request, page_pk):
    try:
        page = HelpBasePage.objects.get(pk=page_pk).specific
    except HelpBasePage.DoesNotExist:
        raise Http404

    model_ct = ContentType.objects.get_for_id(page.content_type_id)
    form_class = get_page_form(model_ct)

    if request.method == "POST":
        form = form_class(data=request.POST, files=request.FILES, instance=page)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("admin:index", kwargs={"page_pk": page.pk}))
    else:
        form = form_class(instance=page)

    return TemplateResponse(
            request,
            "cms/admin/edit_page.html",
            {
                "form": form,
                "page": page,
                "breadcrumbs": breadcrumb_iterator(page),
            }
    ) 
Example #14
Source File: views.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_page(request, model, parent_pk):
    try:
        page = HelpBasePage.objects.get(pk=parent_pk)
    except HelpBasePage.DoesNotExist:
        raise Http404

    try:
        model_ct = ContentType.objects.get_by_natural_key(app_label="cms", model=model)
    except ContentType.DoesNotExist:
        raise Http404

    form_class = get_page_form(model_ct)

    if request.method == "POST":
        form = form_class(data=request.POST, files=request.FILES)
        form.instance.parent_id = parent_pk
        form.instance.content_type = model_ct
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("admin:index", kwargs={"page_pk": parent_pk}))
    else:
        form = form_class()

    return TemplateResponse(
            request,
            "cms/admin/create_page.html",
            {
                "form": form,
                "breadcrumbs": breadcrumb_iterator(page),
            }
    ) 
Example #15
Source File: abstract.py    From django-crudbuilder with Apache License 2.0 5 votes vote down vote up
def get_model_class(self):
        """Returns model class"""
        try:
            c = ContentType.objects.get(app_label=self.app, model=self.model)
        except ContentType.DoesNotExist:
            # try another kind of resolution
            # fixes a situation where a proxy model is defined in some external app.
            if django.VERSION >= (1, 7):
                return apps.get_model(self.app, self.model)
        else:
            return c.model_class() 
Example #16
Source File: admin.py    From django-seo2 with MIT License 5 votes vote down vote up
def get_model_form(metadata_class):
    model_class = metadata_class._meta.get_model('model')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)
    content_type_choices = [(x._get_pk_val(), smart_text(x)) for x in
                            ContentType.objects.filter(id__in=content_types)]

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                      exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ChoiceField(label=capfirst(_("model")),
                                          choices=content_type_choices)

        class Meta:
            model = model_class
            fields = _fields

        def clean__content_type(self):
            value = self.cleaned_data['_content_type']
            try:
                return ContentType.objects.get(pk=int(value))
            except (ContentType.DoesNotExist, ValueError):
                raise forms.ValidationError("Invalid ContentType")

    return ModelMetadataForm 
Example #17
Source File: permissions.py    From django-collaborative with MIT License 5 votes vote down vote up
def build_permission_groups(app_label):
    # get just the base models, we'll use this to build the
    # base groups
    DynamicModel = ContentType.objects.get(
        app_label=app_label, model="dynamicmodel"
    ).model_class()
    Permission, Group = get_permission_models()

    dynmodels = DynamicModel.objects.exclude(name__endswith="metadata")
    for dynmodel in dynmodels:
        name = dynmodel.name
        meta_name = "%smetadata" % (name)
        contact_meta_name = "%scontactmetadata" % (name)

        try:
            content_type = ContentType.objects.get(
                app_label=app_label,
                model=name,
            )
            content_type_meta = ContentType.objects.get(
                app_label=app_label,
                model=meta_name,
            )
            content_type_contactmeta = ContentType.objects.get(
                app_label=app_label,
                model=contact_meta_name,
            )
        except ContentType.DoesNotExist:
            return

        # create the permission group for this source. it simply bears the
        # name of the source and grants all perms
        perm_group, created = Group.objects.get_or_create(
            name=dynmodel.name
        )
        perms = list(Permission.objects.filter(content_type__in=[
            content_type, content_type_meta, content_type_contactmeta
        ]))
        perm_group.permissions.add(*perms)
        perm_group.save() 
Example #18
Source File: mixins.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def content_type(self):
        try:
            return ContentType.objects.get_for_id(self.content_type_id)
        except ContentType.DoesNotExist:
            raise Http404 
Example #19
Source File: pages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_page(self):
        (content_type_app_name, content_type_model_name,
         parent_page_id) = self.args
        try:
            content_type = ContentType.objects.get_by_natural_key(
                content_type_app_name, content_type_model_name)
        except ContentType.DoesNotExist:
            raise Http404

        page = content_type.model_class()()
        parent_page = get_object_or_404(Page, id=parent_page_id).specific
        # We need to populate treebeard's path / depth fields in order to
        # pass validation. We can't make these 100% consistent with the rest
        # of the tree without making actual database changes (such as
        # incrementing the parent's numchild field), but by calling treebeard's
        # internal _get_path method, we can set a 'realistic' value that will
        # hopefully enable tree traversal operations
        # to at least partially work.
        page.depth = parent_page.depth + 1
        # Puts the page at the maximum possible path
        # for a child of `parent_page`.
        page.path = Page._get_children_path_interval(parent_page.path)[1]
        return page 
Example #20
Source File: models.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _get_relobjs(obj,field,filters=None):
    """Find related objects that match
    
    Could be linked using a "related_name" or as <type>_set
    
    django versions have changed this around so somewhat tricky..
    """
    # then try to find objects of this type with a foreign key property using either (name) supplied or target object type
    
    if not filters:
        filters = { 'includes': {} , 'excludes' : {} }
    if field.endswith(")") :
        (field, relprop ) = str(field[0:-1]).split("(")
    else :
        relprop = None
                   
    try:
        reltype = ContentType.objects.get(model=field)
    except ContentType.DoesNotExist as e :
        raise ValueError("Could not locate attribute or related model '{}' in element '{}'".format(field, type(obj)) )

    # if no related_name set in related model then only one candidate and djanog creates X_set attribute we can use
    try:
        return getattr(obj, "".join((field,"_set"))).filter(**filters['includes']).exclude(**filters['excludes'])
    except:
        pass
    
    # trickier then - need to look at models of the named type
    claz = reltype.model_class()
    for prop,val in list(claz.__dict__.items()) :
        # skip related property names if set   
        if relprop and prop != relprop :
            continue
        if relprop or type(val) is ReverseSingleRelatedObjectDescriptor and val.field.related.model == type(obj) :
            filters['includes'].update({prop:obj})
            return claz.objects.filter(**filters['includes']).exclude(**filters['excludes']) 
Example #21
Source File: admin.py    From django-seo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_model_form(metadata_class):
    model_class = metadata_class._meta.get_model('model')

    # Restrict content type choices to the models set in seo_models
    content_types = get_seo_content_types(metadata_class._meta.seo_models)
    content_type_choices = [(x._get_pk_val(), smart_str(x)) for x in
                            ContentType.objects.filter(id__in=content_types)]

    # Get a list of fields, with _content_type at the start
    important_fields = ['_content_type'] + core_choice_fields(metadata_class)
    _fields = important_fields + list(fields_for_model(model_class,
                                                  exclude=important_fields).keys())

    class ModelMetadataForm(forms.ModelForm):
        _content_type = forms.ChoiceField(label=capfirst(_("model")),
                                          choices=content_type_choices)

        class Meta:
            model = model_class
            fields = _fields

        def clean__content_type(self):
            value = self.cleaned_data['_content_type']
            try:
                return ContentType.objects.get(pk=int(value))
            except (ContentType.DoesNotExist, ValueError):
                raise forms.ValidationError("Invalid ContentType")

    return ModelMetadataForm 
Example #22
Source File: 0012_add_permission_view_xform.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def forwards(self, orm):
        pass
        # remove old permission label if migrated with old model metadata
        try:
            ct = ContentType.objects.get(model='xform', app_label='odk_logger')
            Permission.objects.get(content_type=ct, codename='can_view').delete()
            # add new permission label
            perm, created = Permission.objects.get_or_create(content_type=ct, codename='view_xform', name='Can view associated data')
        except (ContentType.DoesNotExist, Permission.DoesNotExist):
            pass