Python django.core.exceptions 模块,ObjectDoesNotExist() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.core.exceptions.ObjectDoesNotExist()

项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_user_exists(request):
    """
    Checks if user is exists. If exists return True, else False.
    """
    if request.is_ajax():
        is_user_exists_form = IsUserExistsForm(request.GET)

        if is_user_exists_form.is_valid():
            try:
                User.objects.get(username=is_user_exists_form.cleaned_data['username'])
                return HttpResponse(json.dumps(True), content_type='application/json')

            except ObjectDoesNotExist:
                return HttpResponse(json.dumps(False), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_mail_exists(request):
    """
    Checks if mail is exists. If exists return True, else False.
    """
    if request.is_ajax():
        is_mail_exists_form = IsMailExistsForm(request.GET)

        if is_mail_exists_form.is_valid():
            try:
                User.objects.get(email=is_mail_exists_form.cleaned_data['email'])
                return HttpResponse(json.dumps(True), content_type='application/json')

            except ObjectDoesNotExist:
                return HttpResponse(json.dumps(False), content_type='application/json')
    else:
        return HttpResponse(status=404)


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def set_rating(request, rating_form):
    """
    Checks if rating for books exists. If exists, changes it. If not, creates a new one.
    """
    try:
        book_rating = BookRating.objects.get(id_user=TheUser.objects.get(id_user=request.user),
                                             id_book=Book.objects.get(id=rating_form.cleaned_data['book']))
        book_rating.rating = rating_form.cleaned_data['rating']
        book_rating.save()

    except ObjectDoesNotExist:
        BookRating.objects.create(id_user=TheUser.objects.get(id_user=request.user),
                                  id_book=Book.objects.get(id=rating_form.cleaned_data['book']),
                                  rating=rating_form.cleaned_data['rating'])

    finally:
        logger.info("User '{}' set rating '{}' to book with id: '{}'."
                    .format(request.user, rating_form.cleaned_data['rating'], rating_form.cleaned_data['book']))


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def get_related_objects_for_create(user_id, book_form):
        """
        Selects related objects to book instance when create new book; creates author object if needed.

        :param int user_id: The id of user.
        :param app.forms.AddBookForm book_form: The form with received data.

        :return: A dict of objects related to book.
        """
        try:
            author = Author.objects.get(author_name__iexact=book_form.cleaned_data['author'])
        except ObjectDoesNotExist:
            author = Author.objects.create(author_name=book_form.cleaned_data['author'])

            logger.info("Created new author with name: '{}' and id: '{}'."
                        .format(author.author_name, author.id))

        category = Category.objects.get(category_name=book_form.cleaned_data['category'])
        lang = Language.objects.get(language=book_form.cleaned_data['language'])
        user = TheUser.objects.get(id_user=user_id)

        return {'author': author, 'category': category, 'lang': lang, 'user': user}

    # ------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def get_related_objects_create_api(user, data):
        """
        Selects related object for book instance when create a new book; creates author object if needed.
        """
        try:
            author = Author.objects.get(author_name__iexact=data.get('author'))
        except ObjectDoesNotExist:
            author = Author.objects.create(author_name=data.get('author'))

            logger.info("Created new author with name: '{}' and id: '{}'."
                        .format(author.author_name, author.id))

        category = Category.objects.get(category_name=data.get('category'))
        lang = Language.objects.get(language=data.get('language'))

        return {'author': author, 'category': category, 'lang': lang}

    # ------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_user_exists(request):
    """
    Checks if user is exists. If exists return True, else False.
    """
    try:
        User.objects.get(username=request.data.get('username'))
        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'user': True}})

    except ObjectDoesNotExist:
        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'user': False}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def is_mail_exists(request):
    """
    Checks if mail is exists. If exists return True, else False.
    """
    try:
        User.objects.get(email=request.data.get('email'))
        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'email': True}})

    except ObjectDoesNotExist:
        return Response({'status': 200,
                         'detail': 'successful',
                         'data': {'email': False}})


# ----------------------------------------------------------------------------------------------------------------------
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def resolve_user_or_group(self, old_id):
        """Resolve a user by its user id from old dudel."""
        # connect to db
        conn = psycopg2.connect(self.conn_string)
        cursor = conn.cursor()

        cursor.execute('SELECT username FROM "user" WHERE id=%s', (old_id,))
        username = cursor.fetchone()
        try:
            if username:
                return get_user_model().objects.get(username=username[0])
            else:
                cursor.execute('SELECT name FROM "group" WHERE id=%s', (old_id,))
                groupname = cursor.fetchone()
                if groupname:
                    return Group.objects.get(name=groupname[0])
        except ObjectDoesNotExist:
            return None
项目:webtzite    作者:materialsproject    | 项目源码 | 文件源码
def connect(self, **kwargs):
        """Connect to standard set of databases. Optionally override in
        derived class named "Connector" to connect to own databases (mostly
        useful for custom REST interfaces). Define or import "Connector" class
        in app's `views.py` (where @mapi_func is used)."""
        try:
            self.default_db = self.get_database('mpcontribs_read')
        except ObjectDoesNotExist:
            try:
                from home.models import DBConfig
            except ImportError:
                from models import DBConfig
            dbconf = DBConfig(
                release=self.release, db_type='mpcontribs_read',
                config="host: 0.0.0.0\ndb: mpcontribs\nport: 27017"
            )
            dbconf.save()
            self.default_db = self.get_database('mpcontribs_read')
项目:educa-coursware    作者:kkampardi    | 项目源码 | 文件源码
def pre_save(self, model_instance, add):
        if getattr(model_instance, self.attname) is None:
            # no current value
            try:
                qs = self.model.objects.all()
                if self.for_fields:
                    # filter by objects with the same field
                    # values for the fields in "for_fields"
                    query = {field: getattr(model_instance, field) for field in self.for_fields}
                    qs = qs.filter(**query)
                # get the order of the last item
                last_item = qs.latest(self.attname)
                value = last_item.order + 1
            except ObjectDoesNotExist:
                value = 0
            setattr(model_instance, self.attname, value)
            return value
        else:
            return super(OrderField, self).pre_save(model_instance, add)
项目:Django-Efficient-Rest    作者:G4brym    | 项目源码 | 文件源码
def get_process_single(self, id):
        #####
        # Retrieves a single object
        #####

        try:
            clean_id = int(id)
        except:
            return status.HTTP_400_BAD_REQUEST

        try:
            object = self.Meta.Model.objects.get(id=clean_id)
        except ObjectDoesNotExist:
            return status.HTTP_404_NOT_FOUND

        self.setResult(object.get_as_dict())
        return status.HTTP_200_OK
项目:Django-Efficient-Rest    作者:G4brym    | 项目源码 | 文件源码
def delete_process_single(self, id):
        #####
        # Deletes a single product
        #####

        try:
            clean_id = int(id)
        except:
            return status.HTTP_400_BAD_REQUEST

        try:
            object = self.Meta.Model.objects.get(id=clean_id)
        except ObjectDoesNotExist:
            return status.HTTP_404_NOT_FOUND

        object.delete()

        return status.HTTP_200_OK
项目:higlass-server    作者:hms-dbmi    | 项目源码 | 文件源码
def suggest(request):
    '''
    Suggest gene names based on the input text
    '''
    # suggestions are taken from a gene annotations tileset
    tileset_uuid = request.GET['d']
    text = request.GET['ac']

    try:
        tileset = tm.Tileset.objects.get(uuid=tileset_uuid)
    except ObjectDoesNotExist:
        raise rfe.NotFound('Suggestion source file not found')

    result_dict = tsu.get_gene_suggestions(
        tut.get_datapath(tileset.datafile.url), text
    )

    return JsonResponse(result_dict, safe=False)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
            )
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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)
            )
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def clean(self):
        cleaned_data = super(AddToCartForm, self).clean()
        quantity = cleaned_data.get('quantity')
        if quantity is None:
            return cleaned_data
        try:
            product_variant = self.get_variant(cleaned_data)
        except ObjectDoesNotExist:
            msg = self.error_messages['variant-does-not-exists']
            self.add_error(NON_FIELD_ERRORS, msg)
        else:
            cart_line = self.cart.get_line(product_variant)
            used_quantity = cart_line.quantity if cart_line else 0
            new_quantity = quantity + used_quantity
            try:
                product_variant.check_quantity(new_quantity)
            except InsufficientStock as e:
                remaining = e.item.get_stock_quantity() - used_quantity
                if remaining:
                    msg = self.error_messages['insufficient-stock']
                    self.add_error('quantity', msg % remaining)
                else:
                    msg = self.error_messages['empty-stock']
                    self.add_error('quantity', msg)
        return cleaned_data
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def move_to_group(self, item, target_group, quantity):
        try:
            target_item = target_group.items.get(
                product=item.product, product_name=item.product_name,
                product_sku=item.product_sku)
        except ObjectDoesNotExist:
            target_group.items.create(
                delivery_group=target_group, product=item.product,
                product_name=item.product_name, product_sku=item.product_sku,
                quantity=quantity, unit_price_net=item.unit_price_net,
                stock=item.stock,
                unit_price_gross=item.unit_price_gross)
        else:
            target_item.quantity += quantity
            target_item.save()
        item.quantity -= quantity
        self.remove_empty_groups(item)
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def speaker_create_staff(request, pk):
    user = get_object_or_404(User, pk=pk)
    if not request.user.is_staff:
        raise Http404

    try:
        return redirect(user.speaker_profile)
    except ObjectDoesNotExist:
        pass

    if request.method == "POST":
        form = SpeakerForm(request.POST, request.FILES)

        if form.is_valid():
            speaker = form.save(commit=False)
            speaker.user = user
            speaker.save()
            messages.success(request, "Speaker profile created.")
            return redirect("user_list")
    else:
        form = SpeakerForm(initial={"name": user.get_full_name()})

    return render(request, "speakers/speaker_create.html", {
        "form": form,
    })
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def speaker_create_token(request, token):
    speaker = get_object_or_404(Speaker, invite_token=token)
    request.session["pending-token"] = token
    if request.user.is_authenticated():
        # check for speaker profile
        try:
            existing_speaker = request.user.speaker_profile
        except ObjectDoesNotExist:
            pass
        else:
            del request.session["pending-token"]
            additional_speakers = ProposalBase.additional_speakers.through
            additional_speakers._default_manager.filter(
                speaker=speaker
            ).update(
                speaker=existing_speaker
            )
            messages.info(request, "You have been associated with all pending "
                "talk proposals")
            return redirect("dashboard")
    else:
        if not request.user.is_authenticated():
            return redirect("account_login")
    return redirect("speaker_create")
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def proposal_submit(request):
    if not request.user.is_authenticated():
        return redirect("home")  # @@@ unauth'd speaker info page?
    else:
        try:
            request.user.speaker_profile
        except ObjectDoesNotExist:
            return redirect("dashboard")

    kinds = []
    for proposal_section in ProposalSection.available():
        for kind in proposal_section.section.proposal_kinds.all():
            kinds.append(kind)

    return render(request, "proposals/proposal_submit.html", {
        "kinds": kinds,
    })
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def proposal_leave(request, pk):
    queryset = ProposalBase.objects.select_related("speaker")
    proposal = get_object_or_404(queryset, pk=pk)
    proposal = ProposalBase.objects.get_subclass(pk=proposal.pk)

    try:
        speaker = proposal.additional_speakers.get(user=request.user)
    except ObjectDoesNotExist:
        return HttpResponseForbidden()
    if request.method == "POST":
        proposal.additional_speakers.remove(speaker)
        # @@@ fire off email to submitter and other speakers
        messages.success(request, "You are no longer speaking on %s" % proposal.title)
        return redirect("dashboard")
    ctx = {
        "proposal": proposal,
    }
    return render(request, "proposals/proposal_leave.html", ctx)
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def proposal_submit(request):
    if not request.user.is_authenticated():
        return redirect("home")  # @@@ unauth'd speaker info page?
    else:
        try:
            request.user.speaker_profile
        except ObjectDoesNotExist:
            return redirect("dashboard")

    kinds = []
    for proposal_section in ProposalSection.available():
        for kind in proposal_section.section.proposal_kinds.all():
            kinds.append(kind)

    return render(request, "proposals/proposal_submit.html", {
        "kinds": kinds,
    })
项目:zing    作者:evernote    | 项目源码 | 文件源码
def reject_suggestion(request, unit, suggid):
    try:
        sugg = unit.suggestion_set.get(id=suggid)
    except ObjectDoesNotExist:
        raise Http404

    # In order to be able to reject a suggestion, users have to either:
    # 1. Have `review` rights, or
    # 2. Be the author of the suggestion being rejected
    if (not check_permission('review', request) and
        (request.user.is_anonymous or request.user != sugg.user)):
        raise PermissionDenied(_('Insufficient rights to access review mode.'))

    unit.reject_suggestion(sugg, request.translation_project, request.user)
    r_data = QueryDict(request.body)
    if "comment" in r_data and r_data["comment"]:
        handle_suggestion_comment(request, sugg, unit, r_data["comment"],
                                  "rejected")

    json = {
        'udbid': unit.id,
        'sugid': suggid,
        'user_score': request.user.public_score,
    }
    return JsonResponse(json)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def accept_suggestion(request, unit, suggid):
    try:
        suggestion = unit.suggestion_set.get(id=suggid)
    except ObjectDoesNotExist:
        raise Http404

    unit.accept_suggestion(suggestion, request.translation_project, request.user)
    if "comment" in request.POST and request.POST["comment"]:
        handle_suggestion_comment(request, suggestion, unit,
                                  request.POST["comment"], "accepted")

    json = {
        'udbid': unit.id,
        'sugid': suggid,
        'user_score': request.user.public_score,
        'newtargets': [target for target in unit.target.strings],
        'checks': _get_critical_checks_snippet(request, unit),
    }
    return JsonResponse(json)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def pluralize_target(unit, nplurals=None):
    if not unit.hasplural():
        return [(0, unit.target, None)]

    if nplurals is None:
        try:
            nplurals = unit.store.translation_project.language.nplurals
        except ObjectDoesNotExist:
            pass
    forms = []
    if nplurals is None:
        for i, target in enumerate(unit.target.strings):
            forms.append((i, target, _('Plural Form %d', i)))
    else:
        for i in range(nplurals):
            try:
                target = unit.target.strings[i]
            except IndexError:
                target = ''
            forms.append((i, target, _('Plural Form %d', i)))

    return forms
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def get_queryset(self):
        if settings.ENV_TYPE == 'debug' or settings.ENV_TYPE == 'dev':
            queryset = self.queryset
            try:
                parent = self.request.user.parent
            except (AttributeError, exceptions.ObjectDoesNotExist):
                parent = None
            if parent is not None:
                queryset = queryset.filter(parent=parent)
        else:
            parent = self.get_parent()
            queryset = self.queryset.filter(parent=parent)

        subject_id = self.request.query_params.get('subject', None)
        if subject_id is not None:
            subject = get_object_or_404(models.Subject, pk=subject_id)
            queryset = queryset.filter(
                exercise_session__live_course_timeslot__live_course__subject=subject
            )

        return queryset.order_by('-updated_at')
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
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)
项目:django-shared-schema-tenants    作者:hugobessa    | 项目源码 | 文件源码
def create(self, tenant=None, *args, **kwargs):
        if not tenant:
            tenant = get_current_tenant()
            if tenant:
                with transaction.atomic():
                    try:
                        model_instance = self.get_original_queryset().get(**kwargs)
                    except ObjectDoesNotExist:
                        model_instance = super(MultipleTenantModelManager, self).create(*args, **kwargs)
                    model_instance.tenants.add(tenant)
                    return model_instance
            else:
                raise TenantNotFoundError()
        else:
            model_instance = super(MultipleTenantModelManager, self).create(*args, **kwargs)
            model_instance.tenants.add(tenant)
            return model_instance
项目:hiwi-stunden    作者:janisstreib    | 项目源码 | 文件源码
def getWorkLog(self, contract, month, year):
        try:
            if contract.contract_begin.year > year or \
                            contract.contract_end.year < year or \
                    (contract.contract_begin.year == year and contract.contract_begin.month > month) or \
                    (contract.contract_end.year == year and contract.contract_end.month < month):
                raise ValidationError("Invalid workLog (shouldn't happen)")
            workL = WorkLog.objects.get(contract=contract, month=month, year=year)
            workSum = workL.calcHours()
        except ObjectDoesNotExist:
            workL = WorkLog()
            workL.month = month
            workL.year = year
            workL.contract = contract
            workL.save()
        return workL
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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)
            )
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
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)
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
def process_request(self, request):

        remote_ip = request.META['REMOTE_ADDR']  # ????ip
        # ?????ip???session????????????,??????
        if remote_ip not in request.session:
            request.session[remote_ip] = 1
            try:
                # ?????????
                visit = VisitStatistics.objects.get(created_date=timezone.now())
                visit.today_visit += 1
                visit.save()
            except ObjectDoesNotExist:
                # ???????????
                visit = VisitStatistics(created_date=timezone.now())
                visit.today_visit += 1
                visit.save()
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
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_unicode(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)
项目:django-bom    作者:mpkasp    | 项目源码 | 文件源码
def add_subpart(request, part_id):
    user = request.user
    profile = user.bom_profile()
    organization = profile.organization

    try:
        part = Part.objects.get(id=part_id)
    except ObjectDoesNotExist:
        messages.error(request, "No part found with given part_id.")
        return HttpResponseRedirect(reverse('error'))

    if request.method == 'POST':
        form = AddSubpartForm(request.POST, organization=organization, part_id=part_id)
        if form.is_valid():
            new_part = Subpart.objects.create(
                assembly_part=part,
                assembly_subpart=form.cleaned_data['assembly_subpart'],
                count=form.cleaned_data['count']
            )

    return HttpResponseRedirect(reverse('part-info', kwargs={'part_id': part_id}) + '#bom')
项目:django-bom    作者:mpkasp    | 项目源码 | 文件源码
def upload_file_to_part(request, part_id):
    try:
        part = Part.objects.get(id=part_id)
    except ObjectDoesNotExist:
        messages.error(request, "No part found with given part_id.")
        return HttpResponseRedirect(reverse('error'))

    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            partfile = PartFile(file=request.FILES['file'], part=part)
            partfile.save()
            return HttpResponseRedirect(reverse('part-info', kwargs={'part_id': part_id}) + '#specs')

    messages.error(request, "Error uploading file.")
    return HttpResponseRedirect(reverse('error'))
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def get_social_username(user):
    """
    Get social auth edX username for a user, or else return None.

    Args:
        user (django.contrib.auth.models.User):
            A Django user
    """
    if user.is_anonymous():
        return None

    try:
        return get_social_auth(user).uid
    except ObjectDoesNotExist:
        return None
    except Exception as ex:  # pylint: disable=broad-except
        log.error("Unexpected error retrieving social auth username: %s", ex)
        return None
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
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)
项目:pyconapac-2016    作者:pythonkr    | 项目源码 | 文件源码
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'))
项目:shiva-dropped    作者:sansaralab    | 项目源码 | 文件源码
def handle_frontend_event(action_type, person: Person, event_name: str, event_value: str):
    javascripts = list()

    try:
        triggers = Trigger.objects.filter(reaction_side=TRIGGER_REACTION_SIDES['FRONTEND']).get()
    except ObjectDoesNotExist:
        triggers = list()

    if len(triggers):
        for trigger in triggers:
            conditions = trigger.conditions
            if len(conditions['caller_names']):
                for caller_name in conditions['caller_names']:
                    if not compare_condition(event_name, caller_name['name'], caller_name['search']):
                        continue

    return javascripts
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
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)
            )
项目:classgrade    作者:classgrade    | 项目源码 | 文件源码
def generate_txt_comments(request, pk):
    try:
        request.user.prof
        evalassignment = Evalassignment.objects.filter(pk=pk).first()
    except ObjectDoesNotExist:
        student = request.user.student
        evalassignment = Evalassignment.objects.\
            filter(pk=pk, assignment__student=student).first()
    response = HttpResponse(content_type='text/txt')
    response['Content-Disposition'] = 'attachment; filename="comments.txt"'
    writer = csv.writer(response)
    if evalassignment:
        # writer.writerow([evalassignment.grade_assignment_comments])
        for evalquestion in evalassignment.evalquestion_set.all().\
                order_by('question'):
            writer.writerow(['****************************************'])
            writer.writerow(['****************************************'])
            writer.writerow(['Question %s' % evalquestion.question,
                             ' Grade %s' % evalquestion.grade])
            writer.writerow(['****************************************'])
            writer.writerow([evalquestion.comments])
    else:
        writer.writerow(['Oups... you might not be allowed to see this'])
    return response
项目:classgrade    作者:classgrade    | 项目源码 | 文件源码
def get_students(csv_file):
    """
    :param csv_file: csv file with list of students.\
        Each row contains: first_name, last_name, email
    :type csv_file: str
    :rtype: 2 lists existing_students and new_students [[username, email], ..]
    """

    with open(csv_file) as ff:
        reader = csv.reader(ff, delimiter=',')
        existing_students = []
        new_students = []
        for i, row in enumerate(reader):
            row = [unidecode(x.strip()) for x in row[:3]]
            username = "_".join(row[:2])
            username = username.replace(" ", "_")
            email = row[2]
            try:
                u = User.objects.get(username=username)
                Student.objects.get(user=u)
                existing_students.append([u.username, u.email])
            except ObjectDoesNotExist:
                new_students.append([username, email])
    return existing_students, new_students
项目:django-ical    作者:pinkerton    | 项目源码 | 文件源码
def __call__(self, request, *args, **kwargs):
        """
        Copied from django.contrib.syndication.views.Feed

        Supports file_name as a dynamic attr.
        """
        try:
            obj = self.get_object(request, *args, **kwargs)
        except ObjectDoesNotExist:
            raise Http404('Feed object does not exist.')
        feedgen = self.get_feed(obj, request)
        response = HttpResponse(content_type=feedgen.mime_type)
        if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'):
            # if item_pubdate or item_updateddate is defined for the feed, set
            # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED
            response['Last-Modified'] = http_date(
                timegm(feedgen.latest_post_date().utctimetuple()))
        feedgen.write(response, 'utf-8')

        filename = self._get_dynamic_attr('file_name', obj)
        if filename:
            response['Content-Disposition'] = 'attachment; filename="%s"' % filename

        return response
项目:polyglot-server    作者:MontrealCorpusTools    | 项目源码 | 文件源码
def get_corpus_status(request, name=None):
    if request.method == 'GET':
        try:
            corpus = Corpus.objects.get(name=name)
        except ObjectDoesNotExist:
            return HttpResponse('Could not find the specified corpus.', status=status.HTTP_404_NOT_FOUND)

        if corpus.current_task_id is None:
            return JsonResponse(data={'data': 'ready'}, status=status.HTTP_200_OK)
        else:
            res = AsyncResult(corpus.current_task_id)
            if res.state == cstates.SUCCESS:
                corpus.current_task_id = None
                if corpus.status == Corpus.IMPORT_RUNNING:
                    corpus.status = Corpus.IMPORTED
                corpus.save()
                return JsonResponse(data={'data': 'ready'}, status=status.HTTP_200_OK)
            elif res.state == cstates.FAILURE:
                corpus.current_task_id = None
                if corpus.status == Corpus.IMPORT_RUNNING:
                    corpus.status = Corpus.NOT_IMPORTED
                corpus.save()
                return JsonResponse(data={'data': 'error'}, status=status.HTTP_200_OK)
            return JsonResponse(data={'data': 'busy'}, status=status.HTTP_200_OK)
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def update_returns(strategy, direction, date_time, perf):
    try:
        try:
            signl = Signals.objects.get(broker=strategy.broker, symbol=strategy.symbol,
                period=strategy.period, system=strategy.system, direction=direction,
                date_time=date_time)
        except ObjectDoesNotExist:
            signl = None

        if not signl is None:
            df = perf.ix[date_time]

            if direction == 1:
                signl.returns = float(df.LONG_PL)
                signl.save()
                print(colored.green("Updated signal result"))
            elif direction == 2:
                signl.returns = float(df.SHORT_PL)
                signl.save()
                print(colored.green("Updated signal result"))
    except Exception as err:
        print(colored.red("At update_returns {}\n".format(err)))
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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)
项目:State-TalentMAP-API    作者:18F    | 项目源码 | 文件源码
def email_share(self, user, email, type, id):
        # Get our e-mail formatter
        formatter = self.get_email_formatter(type)
        instance = None

        # Attempt to get the object instance we want to share
        try:
            instance = apps.get_model(self.AVAILABLE_TYPES[type]).objects.get(id=id)
        except ObjectDoesNotExist:
            # If it doesn't exist, respond with a 404
            return Response({"message": f"Object with id {id} does not exist"}, status=status.HTTP_404_NOT_FOUND)

        # Create our e-mail body
        email_body = {
            "to": email,
            "subject": f"[TalentMAP] Shared {type}",
            "body": formatter(instance)
        }

        # TODO: Implement actual e-mail sending here when avaiable e-mail servers are clarified

        # Return a 202 ACCEPTED with a copy of the email body
        return Response({"message": f"Position shared externally via email at {email}", "email_body": email_body}, status=status.HTTP_202_ACCEPTED)
项目:State-TalentMAP-API    作者:18F    | 项目源码 | 文件源码
def internal_share(self, user, email, type, id):
        receiving_user = None

        # Attempt to get the object instance we want to share
        try:
            apps.get_model(self.AVAILABLE_TYPES[type]).objects.get(id=id)
        except ObjectDoesNotExist:
            # If it doesn't exist, respond with a 404
            return Response({"message": f"Object with id {id} does not exist"}, status=status.HTTP_404_NOT_FOUND)

        # Attempt to get the receiving user by e-mail address
        try:
            receiving_user = UserProfile.objects.get(user__email=email)
        except ObjectDoesNotExist:
            return Response({"message": f"User with email {email} does not exist"}, status=status.HTTP_404_NOT_FOUND)

        # Create our sharable object using the source user, receiving user, id, and model
        # This will auto-populate in the receiving user's received shares on their profile
        Sharable.objects.create(sharing_user=user.profile,
                                receiving_user=receiving_user,
                                sharable_id=id,
                                sharable_model=self.AVAILABLE_TYPES[type])

        return Response({"message": f"Position shared internally to user with email {email}"}, status=status.HTTP_202_ACCEPTED)