本文整理匯總了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