Python django.core.exceptions.ObjectDoesNotExist() Examples

The following are 30 code examples of django.core.exceptions.ObjectDoesNotExist(). 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.core.exceptions , or try the search function .
Example #1
Source File: layermapping.py    From GTDWeb with GNU General Public License v2.0 7 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        this routine will retrieve the related model for the ForeignKey
        mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example #2
Source File: abstract_job_view.py    From black-widow with GNU General Public License v3.0 6 votes vote down vote up
def _get_job(self, request, redirect_url: str):
        """
        Show the requested job
        :type request: django.core.handlers.wsgi.WSGIRequest
        :param redirect_url: The url to redirect the request in case of errors
        :return: django.http.HttpResponse
        """
        request_params: dict = request.GET.dict()

        try:
            job_id = int(request_params.get('id'))
        except (ValueError, TypeError) as e:
            Log.error(str(e))
            return redirect(redirect_url)

        Log.info("Showing job #" + str(job_id))

        try:
            job = self.model_class.objects.get(id=job_id)
        except ObjectDoesNotExist:
            return redirect(redirect_url)

        return render(request, self.template_name, {
            'job': job
        }) 
Example #3
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_grainfather_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GrainfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Grainfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.GrainfatherPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.GrainfatherPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/grainfather_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example #4
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_grainfather_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GrainfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Grainfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "Grainfather push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example #5
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_thingspeak_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = ThingSpeakPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "ThingSpeak push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "ThingSpeak push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example #6
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_thingspeak_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = ThingSpeakPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "ThingSpeak push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.ThingSpeakPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.ThingSpeakPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/thingspeak_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example #7
Source File: views.py    From pyconkr-2015 with MIT License 6 votes vote down vote up
def login_req(request, token):
    time_threshold = datetime.now() - timedelta(hours=1)

    try:
        token = EmailToken.objects.get(token=token,
                                       created__gte=time_threshold)
    except ObjectDoesNotExist:
        return render(request, 'login_notvalidtoken.html',
                      {'title': _('Not valid token')})
    email = token.email

    # Create user automatically by email as id, token as password
    try:
        user = User.objects.get(email=email)
    except ObjectDoesNotExist:
        user = User.objects.create_user(email, email, token)
        user.save()

    token.delete()

    # Set backend manually
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    user_login(request, user)

    return redirect(reverse('index')) 
Example #8
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_brewfather_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewfatherPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewfather push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.BrewfatherPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.BrewfatherPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/brewfather_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example #9
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_brewers_friend_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewersFriendPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewers's Friend push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = "Brewers's Friend push target {} has been deleted".format(push_target_id)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example #10
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_brewers_friend_view(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = BrewersFriendPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "Brewers's Friend push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    if request.POST:
        form = forms.BrewersFriendPushTargetModelForm(request.POST, instance=push_target)
        if form.is_valid():
            updated_push_target = form.save()
            messages.success(request, 'Updated push target')
            return redirect('external_push_list')

        messages.error(request, 'Unable to update push target')

    form = forms.BrewersFriendPushTargetModelForm(instance=push_target)

    return render(request, template_name='external_push/brewers_friend_push_target_view.html',
                  context={'push_target': push_target, 'form': form}) 
Example #11
Source File: resource.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, request, resourceid=None):
        lang = request.GET.get("lang", settings.LANGUAGE_CODE)
        se = SearchEngineFactory().create()
        req = dict(request.GET)
        ids_to_delete = req["resourcexids[]"]
        root_resourceinstanceid = req["root_resourceinstanceid"]
        for resourcexid in ids_to_delete:
            try:
                ret = models.ResourceXResource.objects.get(pk=resourcexid).delete()
            except ObjectDoesNotExist:
                logger.exception(_("Unable to delete. Relationship does not exist"))
        start = request.GET.get("start", 0)
        se.es.indices.refresh(index=se._add_prefix("resource_relations"))
        resource = Resource.objects.get(pk=root_resourceinstanceid[0])
        page = 1 if request.GET.get("page") == "" else int(request.GET.get("page", 1))
        related_resources = resource.get_related_resources(lang=lang, start=start, limit=1000, page=page)
        ret = []

        if related_resources is not None:
            ret = self.paginate_related_resources(related_resources, page, request)

        return JSONResponse(ret, indent=4) 
Example #12
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def gravity_log_delete(request, log_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_beer'):
    #     messages.error(request, 'Your account is not permissioned to add beers. Please contact an admin')
    #     return redirect("/")

    try:
        log_obj = GravityLog.objects.get(id=log_id)

        if log_obj.device:
            if log_obj.device.active_log == log_obj:
                # If the log is currently being logged to, we don't want to trigger a delete
                messages.error(request, u'Requested log is currently in use - Stop logging on device and reattempt')
                return redirect('gravity_log_list')

        log_obj.delete()
        messages.success(request, u'Log "{}" was deleted'.format(log_obj.name))
    except:
        # TODO - Rewrite this to make it more specific (ObjectDoesNotExist error, for example)
        messages.error(request, u'Unable to delete log with ID {}'.format(log_id))
    return redirect('gravity_log_list') 
Example #13
Source File: views.py    From fermentrack with MIT License 6 votes vote down vote up
def external_push_delete(request, push_target_id):
    # TODO - Add user permissioning
    # if not request.user.has_perm('app.add_device'):
    #     messages.error(request, 'Your account is not permissioned to add devices. Please contact an admin')
    #     return redirect("/")

    try:
        push_target = GenericPushTarget.objects.get(id=push_target_id)
    except ObjectDoesNotExist:
        messages.error(request, "External push target {} does not exist".format(push_target_id))
        return redirect('external_push_list')

    message = 'Push target {} has been deleted'.format(push_target.name)
    push_target.delete()
    messages.success(request, message)

    return redirect('external_push_list') 
Example #14
Source File: datatypes.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def validate(self, value, row_number=None, source="", node=None, nodeid=None):
        errors = []
        if value is not None:
            resourceXresourceIds = self.get_id_list(value)
            for resourceXresourceId in resourceXresourceIds:
                resourceid = resourceXresourceId["resourceId"]
                try:
                    models.ResourceInstance.objects.get(pk=resourceid)
                except ObjectDoesNotExist:
                    errors.append(
                        {
                            "type": "WARNING",
                            "message": f"The resource id: {resourceid} does not exist in the system. The data for this card will \
                                be available in the system once resource {resourceid} is loaded.",
                        }
                    )
        return errors 
Example #15
Source File: layermapping.py    From bioforum with MIT License 6 votes vote down vote up
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        retrieve the related model for the ForeignKey mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
Example #16
Source File: helpers.py    From bioforum with MIT License 6 votes vote down vote up
def contents(self):
        from django.contrib.admin.templatetags.admin_list import _boolean_icon
        field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
        try:
            f, attr, value = lookup_field(field, obj, model_admin)
        except (AttributeError, ValueError, ObjectDoesNotExist):
            result_repr = self.empty_value_display
        else:
            if f is None:
                boolean = getattr(attr, "boolean", False)
                if boolean:
                    result_repr = _boolean_icon(value)
                else:
                    if hasattr(value, "__html__"):
                        result_repr = value
                    else:
                        result_repr = linebreaksbr(value)
            else:
                if isinstance(f.remote_field, ManyToManyRel) and value is not None:
                    result_repr = ", ".join(map(str, value.all()))
                else:
                    result_repr = display_for_field(value, f, self.empty_value_display)
                result_repr = linebreaksbr(result_repr)
        return conditional_escape(result_repr) 
Example #17
Source File: editable.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def _get_new_field_html(self, field_name):
        try:
            f, attr, value = lookup_field(field_name, self.org_obj, self)
        except (AttributeError, ObjectDoesNotExist):
            return EMPTY_CHANGELIST_VALUE
        else:
            allow_tags = False
            if f is None:
                allow_tags = getattr(attr, 'allow_tags', False)
                boolean = getattr(attr, 'boolean', False)
                if boolean:
                    allow_tags = True
                    text = boolean_icon(value)
                else:
                    text = smart_text(value)
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(self.org_obj, f.name)
                    if field_val is None:
                        text = EMPTY_CHANGELIST_VALUE
                    else:
                        text = field_val
                else:
                    text = display_for_field(value, f)
            return mark_safe(text) if allow_tags else conditional_escape(text) 
Example #18
Source File: createtestdata.py    From silverstrike with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        if options['prune']:
            self._prune()
        self._initialize()
        today = date.today()
        try:
            start_date = Transaction.objects.filter(
                date__lte=today).latest('date').date.replace(day=1)
        except ObjectDoesNotExist:
            start_date = date(2016, 1, 1)

        while start_date < today:
            self._create_monthly(start_date.year, start_date.month)
            start_date += relativedelta(months=+1)
        Transaction.objects.bulk_create(self.transactions)
        Split.objects.bulk_create(self.splits) 
Example #19
Source File: kulke.py    From linkedevents with MIT License 6 votes vote down vote up
def import_keywords(self):
        logger.info("Importing Kulke categories as keywords")
        categories = self.parse_kulke_categories()
        for kid, value in categories.items():
            try:
                # if the keyword exists, update the name if needed
                word = Keyword.objects.get(id=make_kulke_id(kid))
                if word.name != value['text']:
                    word.name = value['text']
                    word.save()
                if word.publisher_id != self.organization.id:
                    word.publisher = self.organization
                    word.save()
            except ObjectDoesNotExist:
                # if the keyword does not exist, save it for future use
                Keyword.objects.create(
                    id=make_kulke_id(kid),
                    name=value['text'],
                    data_source=self.data_source,
                    publisher=self.organization
                ) 
Example #20
Source File: testing.py    From peering-manager with Apache License 2.0 6 votes vote down vote up
def test_delete_object(self):
            instance = self.model.objects.first()

            request = {
                "path": self._get_url("delete", instance),
                "data": {"confirm": True},
                "follow": False,  # Do not follow 302 redirects
            }

            # Attempt to make the request without required permissions
            self.assertStatus(self.client.post(**request), 403)

            # Assign the required permission and submit again
            self.add_permissions(
                f"{self.model._meta.app_label}.delete_{self.model._meta.model_name}"
            )
            response = self.client.post(**request)
            self.assertStatus(response, 302)

            with self.assertRaises(ObjectDoesNotExist):
                self.model.objects.get(pk=instance.pk) 
Example #21
Source File: helpers.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def contents(self):
        from django.contrib.admin.templatetags.admin_list import _boolean_icon
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
        try:
            f, attr, value = lookup_field(field, obj, model_admin)
        except (AttributeError, ValueError, ObjectDoesNotExist):
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if f is None:
                boolean = getattr(attr, "boolean", False)
                if boolean:
                    result_repr = _boolean_icon(value)
                else:
                    result_repr = smart_text(value)
                    if getattr(attr, "allow_tags", False):
                        result_repr = mark_safe(result_repr)
                    else:
                        result_repr = linebreaksbr(result_repr)
            else:
                if isinstance(f.rel, ManyToManyRel) and value is not None:
                    result_repr = ", ".join(map(six.text_type, value.all()))
                else:
                    result_repr = display_for_field(value, f)
        return conditional_escape(result_repr) 
Example #22
Source File: fields.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            f = self.model._meta.get_field(self.ct_field)
            ct_id = getattr(instance, f.get_attname(), None)
            if ct_id is not None:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj 
Example #23
Source File: annotations.py    From readux with MIT License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        username = kwargs['username']
        try:
            owner = User.objects.get(username=username)
            if self.request.user == owner: 
                return JsonResponse(
                    json.loads(
                        serialize(
                            'user_annotation_list',
                            self.get_queryset(),
                            owners=[owner]
                        )
                    ),
                    safe=False
                )
            else:
                return JsonResponse(status=401, data={"Permission to see annotations not allowed for logged in user.": username})

        except ObjectDoesNotExist:
            # attempt to get annotations for non-existent user
            return JsonResponse(status=404, data={"User not found.": username})
        return JsonResponse(status=200, data={}) 
Example #24
Source File: test_safe_creation_service.py    From safe-relay-service with MIT License 6 votes vote down vote up
def test_deploy_create2_safe_tx(self):
        random_safe_address = Account.create().address
        with self.assertRaises(ObjectDoesNotExist):
            self.safe_creation_service.deploy_create2_safe_tx(random_safe_address)

        owner_accounts = [Account.create() for _ in range(4)]
        owners = [owner_account.address for owner_account in owner_accounts]

        salt_nonce = 17051863
        threshold = 2
        payment_token = None
        safe_creation_2 = self.safe_creation_service.create2_safe_tx(salt_nonce, owners, threshold, payment_token)
        safe_address = safe_creation_2.safe_id
        self.assertFalse(self.ethereum_client.is_contract(safe_address))
        self.assertIsNone(safe_creation_2.tx_hash)
        with self.assertRaisesMessage(NotEnoughFundingForCreation, str(safe_creation_2.payment)):
            self.safe_creation_service.deploy_create2_safe_tx(safe_address)
        self.send_ether(safe_address, safe_creation_2.payment)
        new_safe_creation_2 = self.safe_creation_service.deploy_create2_safe_tx(safe_address)
        self.assertTrue(new_safe_creation_2.tx_hash)
        self.assertTrue(self.ethereum_client.is_contract(safe_address))

        # If already deployed it will return `SafeCreation2`
        another_safe_creation2 = self.safe_creation_service.deploy_create2_safe_tx(safe_address)
        self.assertEqual(another_safe_creation2, new_safe_creation_2) 
Example #25
Source File: views.py    From FIR with GNU General Public License v3.0 5 votes vote down vote up
def user_login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if not request.POST.get('remember', None):
                request.session.set_expiry(0)

            try:
                Profile.objects.get(user=user)
            except ObjectDoesNotExist:
                profile = Profile()
                profile.user = user
                profile.hide_closed = False
                profile.incident_number = 50
                profile.save()

            if user.is_active:
                login(request, user)
                log("Login success", user)
                init_session(request)
                return redirect('dashboard:main')
            else:
                log("Login attempted from locked account", user)
                return HttpResponse('Account disabled')
        else:
            log("Login failed for "+username, None)
            return render(request, 'incidents/login.html', {'error': 'error'})
    else:
        return render(request, 'incidents/login.html') 
Example #26
Source File: filters.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def filter_queryset(self, request, queryset, view):
        """
        Anonymous user has no object permissions, return queryset as it is.
        """
        user = request.user
        project_id = view.kwargs.get(view.lookup_field)

        if user.is_anonymous():
            return queryset.filter(Q(shared=True))

        if project_id:
            try:
                int(project_id)
            except ValueError:
                raise ParseError(
                    u"Invalid value for project_id '%s' must be a positive "
                    "integer." % project_id)

            # check if project is public and return it
            try:
                project = queryset.get(id=project_id)
            except ObjectDoesNotExist:
                raise Http404

            if project.shared:
                return queryset.filter(Q(id=project_id))

        return super(AnonUserProjectFilter, self)\
            .filter_queryset(request, queryset, view) 
Example #27
Source File: sensors.py    From fermentrack with MIT License 5 votes vote down vote up
def get_tilt_extras(req, device_id):
    try:
        device = GravitySensor.objects.get(id=device_id)
    except ObjectDoesNotExist:
        return JsonResponse({'error': 'Unable to locate device with ID {}'.format(device_id)}, safe=False)

    if device.sensor_type == GravitySensor.SENSOR_TILT:
        # Load the Tilt 'extras' from redis
        extras = device.tilt_configuration.load_extras_from_redis()
        extras['device_name'] = device.name
        extras['device_id'] = device.id
    else:
        extras = {}

    return JsonResponse(extras, safe=False, json_dumps_params={'indent': 4}) 
Example #28
Source File: xform.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def time_of_last_submission(self):
        if self.last_submission_time is None and self.num_of_submissions > 0:
            try:
                last_submission = self.instances.\
                    filter(deleted_at__isnull=True).latest("date_created")
            except ObjectDoesNotExist:
                pass
            else:
                self.last_submission_time = last_submission.date_created
                self.save()
        return self.last_submission_time 
Example #29
Source File: provider.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def infra_type_implementation(self, provider_uuid, tenant):
        """Return infrastructure type."""
        try:
            provider_model = Provider.objects.get(uuid=provider_uuid)
            resource_name = provider_model.authentication.provider_resource_name
        except (ObjectDoesNotExist, ValidationError) as e:
            raise (OCPProviderError(str(e)))

        if self._is_on_aws(tenant, resource_name):
            return Provider.PROVIDER_AWS
        if self._is_on_azure(tenant, resource_name):
            return Provider.PROVIDER_AZURE

        return None 
Example #30
Source File: xform.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def time_of_last_submission_update(self):
        try:
            # we also consider deleted instances in this case
            return self.instances.latest("date_modified").date_modified
        except ObjectDoesNotExist:
            pass