本文整理汇总了Python中django.db.models.ObjectDoesNotExist方法的典型用法代码示例。如果您正苦于以下问题:Python models.ObjectDoesNotExist方法的具体用法?Python models.ObjectDoesNotExist怎么用?Python models.ObjectDoesNotExist使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.ObjectDoesNotExist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clean
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例2: to_search
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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)
示例3: handle_emails_pre_case_delete
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例4: delete_user
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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()
示例5: __get__
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
def __get__(self, *args, **kwargs):
try:
return super(SingleRelatedObjectDescriptorReturnsNone, self).__get__(
*args, **kwargs
)
except models.ObjectDoesNotExist:
return None
示例6: get_object
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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)
示例7: first_activated
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例8: first_activated
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例9: save
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例10: process_new_token
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例11: process_old_token
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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
示例12: show_determination_button
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
def show_determination_button(user, submission):
try:
return can_edit_determination(user, submission.determinations.active(), submission)
except ObjectDoesNotExist:
return can_create_determination(user, submission)
示例13: test_pre_check_product_with_number
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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))
示例14: test_pre_check_product_with_no_exist
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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"})
示例15: serialize_model
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import ObjectDoesNotExist [as 别名]
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