Python django.db.models.ObjectDoesNotExist() Examples
The following are 21
code examples of django.db.models.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.db.models
, or try the search function
.
Example #1
Source File: forms.py From StormOnline with Apache License 2.0 | 6 votes |
def clean(self): # 判断用户是否登陆 if self.user.is_authenticated: self.cleaned_data['user'] = self.user else: raise forms.ValidationError('用户尚未登陆') content_type = self.cleaned_data['content_type'] object_id = self.cleaned_data['object_id'] try: model_class = ContentType.objects.get(model=content_type).model_class() model_obj = model_class.objects.get(pk=object_id) self.cleaned_data['content_object'] = model_obj except ObjectDoesNotExist: raise forms.ValidationError('评论对象不存在') return self.cleaned_data
Example #2
Source File: tasks.py From feedsubs with MIT License | 6 votes |
def delete_user(user_id: int): try: user = get_user_model().objects.get(pk=user_id) except ObjectDoesNotExist: logger.info('Not deleting user with id %s: already deleted', user_id) return if not user.um_profile.deletion_pending: logger.info('Not deleting user %s: deletion not pending', user) return if user.last_login > now() - UM_DELETE_ACCOUNT_AFTER: logger.info('Not deleting user %s: last login %s', user, user.last_login) return logger.info('Deleting user %s', user) user.delete()
Example #3
Source File: signals.py From Kiwi with GNU General Public License v2.0 | 6 votes |
def handle_emails_pre_case_delete(sender, **kwargs): """ Send email updates before a TestCase will be deleted! """ if kwargs.get('raw', False): return instance = kwargs['instance'] try: # note: using the `email_settings` related object instead of the # `emailing` property b/c it breaks with cascading deletes via admin. # if there are not settings created before hand they default to False # so email will not going to be sent and the exception is safe to ignore if instance.email_settings.notify_on_case_delete: from tcms.testcases.helpers import email email.email_case_deletion(instance) except ObjectDoesNotExist: pass
Example #4
Source File: models.py From es-django-example with Apache License 2.0 | 6 votes |
def to_search(self): d = super(Question, self).to_search() d.update({ 'tags': self.tags, 'title': self.title, 'favorite_count': self.favorite_count, 'view_count': self.view_count, 'answer_count': self.answer_count, 'has_accepted_answer': bool(self.accepted_answer_id), }) if self.last_editor_id: try: d.update({ 'last_editor': self.last_editor.to_search(), 'last_edit_date': self.last_edit_date }) except models.ObjectDoesNotExist: pass return QuestionDoc(**d)
Example #5
Source File: test_utils.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def test_pre_check_product_with_number(self): product = U.pre_check_product(self.product.pk) self.assertEqual(product.name, "World Of Warcraft") self.assertRaises(ObjectDoesNotExist, U.pre_check_product, str(self.product.pk))
Example #6
Source File: utils.py From steemprojects.com with MIT License | 5 votes |
def get_version(package): versions = package.version_set.exclude(upload_time=None) try: return versions.latest() except models.ObjectDoesNotExist: return None
Example #7
Source File: fields.py From donation-tracker with Apache License 2.0 | 5 votes |
def __get__(self, *args, **kwargs): try: return super(SingleRelatedObjectDescriptorReturnsNone, self).__get__( *args, **kwargs ) except models.ObjectDoesNotExist: return None
Example #8
Source File: tasks.py From feedsubs with MIT License | 5 votes |
def create_feed(user_id: int, uri: str): try: user = get_user_model().objects.get(pk=user_id) except ObjectDoesNotExist: logger.warning('Not creating feed "%s" as user %d does not exist', uri, user_id) return # Check if the feed already exists parsed_feed = None try: feed = models.Feed.objects.get(uri=uri) except ObjectDoesNotExist: feed = None else: logger.info('Feed already exists: %s', feed) if feed is None: try: feed, parsed_feed = _fetch_and_create_feed(uri) except FeedFetchError as e: logger.warning('%s', e) background_messages.warning(user, str(e)) return _subscribe_user(user, feed) if parsed_feed is not None: synchronize_parsed_feed(feed, parsed_feed) feed.frequency_per_year = calculate_frequency_per_year(feed) feed.save(update_fields=['frequency_per_year'])
Example #9
Source File: node.py From esdc-ce with Apache License 2.0 | 5 votes |
def storage(self): """Default local storage""" if not self._storage: # cache if self.zpool: try: self._ns = NodeStorage.objects.select_related('storage').get(node=self, zpool=self.zpool) self._storage = self._ns.storage except models.ObjectDoesNotExist: name = ('%s@%s' % (self.zpool, self.hostname))[:64] self._storage = Storage(size=self.zpool_size, owner=self.owner, access=Storage.PUBLIC, name=name, alias=self.zpool, desc='Default local storage pool') else: self._storage = Storage(size_coef='1.0', size=0, type=Storage.LOCAL) return self._storage
Example #10
Source File: models.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def get_text_with_version(self, case_text_version=None): if case_text_version: try: return self.history.get(history_id=case_text_version).text except ObjectDoesNotExist: return self.text return self.text
Example #11
Source File: serializer.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def serialize_model(self): """ Check the fields of models and convert the data Returns: Dictionary """ if not hasattr(self.model, '__dict__'): raise TypeError("Models or Dictionary is required") response = {} opts = self.model._meta for field in opts.local_fields: # for a django model, retrieving a foreignkey field # will fail when the field value isn't set try: value = getattr(self.model, field.name) except ObjectDoesNotExist: value = None if isinstance(value, datetime): value = datetime_to_str(value) if isinstance(value, timedelta): value = timedelta_to_str(value) if isinstance(field, ForeignKey): fk_id = "%s_id" % field.name if value is None: response[fk_id] = None else: response[fk_id] = getattr(self.model, fk_id) value = str(value) response[field.name] = value for field in opts.local_many_to_many: value = getattr(self.model, field.name) value = value.values_list('pk', flat=True) response[field.name] = list(value) return response
Example #12
Source File: test_utils.py From Kiwi with GNU General Public License v2.0 | 5 votes |
def test_pre_check_product_with_no_exist(self): self.assertRaises(ObjectDoesNotExist, U.pre_check_product, {"product": 9999}) self.assertRaises(ObjectDoesNotExist, U.pre_check_product, {"product": "unknown name"})
Example #13
Source File: openedx_deployment.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
def first_activated(self): """ Returns the activation date for the first activated ``AppServer`` for this Deployment, or ``None`` if there is no AppServer, or no AppServer has yet been activated. :return: Union[None, datetime] """ try: first_activated_appserver = self.openedxappserver_set.filter( last_activated__isnull=False ).earliest('last_activated') return first_activated_appserver.last_activated except models.ObjectDoesNotExist: return None
Example #14
Source File: fields.py From pasportaservo with GNU Affero General Public License v3.0 | 5 votes |
def get_object(self, model_instance): try: return super().get_object(model_instance) except models.ObjectDoesNotExist: data = {'pk': -1} data[self.field.to_fields[0]] = getattr(model_instance, self.field.attname) return self.field.remote_field.model(**data)
Example #15
Source File: openedx_instance.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
def first_activated(self): """ Returns the activation date for the first activated ``AppServer`` for this instance, or ``None`` if there is no AppServer, or no AppServer has yet been activated. :return: Union[None, datetime] """ try: first_activated_appserver = self.appserver_set.filter( last_activated__isnull=False ).earliest('last_activated') return first_activated_appserver.last_activated except models.ObjectDoesNotExist: return None
Example #16
Source File: determination_tags.py From hypha with BSD 3-Clause "New" or "Revised" License | 5 votes |
def show_determination_button(user, submission): try: return can_edit_determination(user, submission.determinations.active(), submission) except ObjectDoesNotExist: return can_create_determination(user, submission)
Example #17
Source File: utils.py From PonyConf with Apache License 2.0 | 5 votes |
def process_old_token(token): try: thread = MessageThread.objects.get(token__iexact=token[:32]) sender = MessageCorrespondent.objects.get(token__iexact=token[32:64]) except models.ObjectDoesNotExist: raise InvalidTokenException if token[64:].lower() != hexdigest_sha256(settings.SECRET_KEY, thread.token, sender.token)[:16]: raise InvalidKeyException in_reply_to = thread.message_set.last() author = None if author is None: try: author = User.objects.get(email=sender.email) except User.DoesNotExist: pass if author is None: try: author = Participant.objects.get(email=sender.email) except Participant.DoesNotExist: pass if author is None: try: author = Conference.objects.get(contact_email=sender.email) except Conference.DoesNotExist: raise # this was last hope... author_type = ContentType.objects.get_for_model(author) author, _ = MessageAuthor.objects.get_or_create(author_type=author_type, author_id=author.pk) return in_reply_to, author
Example #18
Source File: utils.py From PonyConf with Apache License 2.0 | 5 votes |
def process_new_token(token): try: in_reply_to = Message.objects.get(token__iexact=token[:32]) author = MessageAuthor.objects.get(token__iexact=token[32:64]) except models.ObjectDoesNotExist: raise InvalidTokenException if token[64:].lower() != hexdigest_sha256(settings.SECRET_KEY, in_reply_to.token, author.token)[:16]: raise InvalidKeyException return in_reply_to, author
Example #19
Source File: models.py From BookForum with MIT License | 5 votes |
def save(self, *args, **kwargs): cover_default_path = self.cover.field.default.replace('/', '\\') if not cover_default_path in self.cover.path: try: origin_book = Book.objects.get(slug=self.slug) if origin_book.cover.path != self.cover.path: # 如果要更改封面,就删除原来的封面 try: os.remove(origin_book.cover.path) except FileNotFoundError: pass except ObjectDoesNotExist: pass # 自动根据书籍的名称和作者添加一个slug slug = '-by-'.join([self.name, self.auther.name]) self.slug = slugify(slug) ret = super(Book, self).save(*args, **kwargs) if not cover_default_path in self.cover.path: # 不剪裁默认封面 COVER_WIDTH = getattr(settings, 'COVER_WIDTH', 210) COVER_HEIGHT = getattr(settings, 'COVER_HEIGHT', 280) crop_img(self.cover, COVER_WIDTH, COVER_HEIGHT) return ret
Example #20
Source File: models.py From Kiwi with GNU General Public License v2.0 | 4 votes |
def clone(self, new_author, test_plans): new_tc = self.__class__.objects.create( is_automated=self.is_automated, script=self.script, arguments=self.arguments, extra_link=self.extra_link, summary=self.summary, requirement=self.requirement, case_status=TestCaseStatus.get_proposed(), category=self.category, priority=self.priority, notes=self.notes, text=self.text, author=new_author, default_tester=self.default_tester, ) # apply tags as well for tag in self.tag.all(): new_tc.add_tag(tag) for plan in test_plans: plan.add_case(new_tc) # clone TC category b/c we may be cloning a 'linked' # TC which has a different Product that doesn't have the # same categories yet try: tc_category = plan.product.category.get(name=self.category.name) except ObjectDoesNotExist: tc_category = plan.product.category.create( name=self.category.name, description=self.category.description, ) new_tc.category = tc_category new_tc.save() # clone TC components b/c we may be cloning a 'linked' # TC which has a different Product that doesn't have the # same components yet for component in self.component.all(): try: new_component = plan.product.component.get(name=component.name) except ObjectDoesNotExist: new_component = plan.product.component.create( name=component.name, initial_owner=new_author, description=component.description, ) new_tc.add_component(new_component) return new_tc
Example #21
Source File: views.py From diting with GNU General Public License v2.0 | 4 votes |
def get(self, request, *args, **kwargs): # 获取数据 user = request.user # print(user) if not user.is_authenticated: return ErrorResponse(400, 'you were not login') content_type = request.GET.get('content_type') object_id = request.GET.get('object_id') try: content_type = ContentType.objects.get(model=content_type) model_class = content_type.model_class() model_obj = model_class.objects.get(pk=object_id) except ObjectDoesNotExist: return ErrorResponse(401, 'object not exist') # 处理数据 if request.GET.get('is_like') == 'true': # 要点赞 like_record, created = LikeRecord.objects.get_or_create(content_type=content_type, object_id=object_id, user=user) if created: # 未点赞过,进行点赞 like_count, created = LikeCount.objects.get_or_create(content_type=content_type, object_id=object_id) like_count.liked_num += 1 like_count.save() return SuccessResponse(like_count.liked_num) else: # 已点赞过,不能重复点赞 return ErrorResponse(402, 'you were liked') else: # 要取消点赞 if LikeRecord.objects.filter(content_type=content_type, object_id=object_id, user=user).exists(): # 有点赞过,取消点赞 like_record = LikeRecord.objects.get(content_type=content_type, object_id=object_id, user=user) like_record.delete() # 点赞总数减1 like_count, created = LikeCount.objects.get_or_create(content_type=content_type, object_id=object_id) if not created: like_count.liked_num -= 1 like_count.save() return SuccessResponse(like_count.liked_num) else: return ErrorResponse(404, 'data error') else: # 没有点赞过,不能取消 return ErrorResponse(403, 'you were not liked')