本文整理汇总了Python中django.core.exceptions.ObjectDoesNotExist方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ObjectDoesNotExist方法的具体用法?Python exceptions.ObjectDoesNotExist怎么用?Python exceptions.ObjectDoesNotExist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.exceptions
的用法示例。
在下文中一共展示了exceptions.ObjectDoesNotExist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: login_req
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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'))
示例2: delete
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例3: validate
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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
示例4: _get_new_field_html
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例5: contents
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例6: verify_fk
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
)
示例7: __get__
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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
示例8: get
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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={})
示例9: test_deploy_create2_safe_tx
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例10: test_delete_object
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例11: import_keywords
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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
)
示例12: handle
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例13: contents
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
示例14: verify_fk
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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)
)
示例15: _get_job
# 需要导入模块: from django.core import exceptions [as 别名]
# 或者: from django.core.exceptions import ObjectDoesNotExist [as 别名]
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
})