本文整理汇总了Python中django.contrib.admin.util.NestedObjects类的典型用法代码示例。如果您正苦于以下问题:Python NestedObjects类的具体用法?Python NestedObjects怎么用?Python NestedObjects使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NestedObjects类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_deleted_objects
def get_deleted_objects(obj, user):
"""
Find all objects related to ``obj`` that should also be deleted.
Returns a nested list of strings suitable for display in the
template with the ``unordered_list`` filter.
Copied and updated from django.contrib.admin.util for front end display.
"""
using = router.db_for_write(obj.__class__)
collector = NestedObjects(using=using)
collector.collect([obj])
perms_needed = set()
def format_callback(obj):
opts = obj._meta
if hasattr(obj, "get_absolute_url"):
url = obj.get_absolute_url()
p = "%s.%s" % (opts.app_label, opts.get_delete_permission())
if not user.has_perm(p):
perms_needed.add(opts.verbose_name)
# Display a link to the admin page.
return mark_safe(u'%s: <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), url, escape(obj)))
else:
# no link
return u"%s: %s" % (capfirst(opts.verbose_name), force_unicode(obj))
to_delete = collector.nested(format_callback)
protected = [format_callback(obj) for obj in collector.protected]
return to_delete, perms_needed, protected
示例2: ui_model_delete_device
def ui_model_delete_device(request, umdid):
uim_device = UIModelDevice.objects.get(id=umdid)
if uim_device.uimodel.is_frozen:
return render(request, 'mcms/uimodels/frozen.html',
dict(uimodel=uim_device.uimodel))
collector = NestedObjects(using='default')
collector.collect([uim_device, ])
to_delete = collector.nested()
if request.method == 'POST': # The user has already confirmed the delete.
uim_device.delete()
return HttpResponseRedirect(
reverse('mcms:uimodels:details', kwargs={
'mid': uim_device.uimodel.id}))
opts = uim_device._meta
object_name = force_unicode(opts.verbose_name)
title = ('Are you sure?')
context = {
'title': title,
'object_name': object_name,
'object': uim_device,
'deleted_objects': to_delete,
'opts': opts,
'app_label': opts.app_label,
}
return TemplateResponse(
request,
'mcms/uimodels/delete_confirmation.html', context, current_app='Test')
示例3: delete_survey
def delete_survey(request, sid):
survey = get_object_or_404(Engagement_Survey, id=sid)
form = Delete_Eng_Survey_Form(instance=survey)
from django.contrib.admin.util import NestedObjects
from django.db import DEFAULT_DB_ALIAS
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([survey])
rels = collector.nested()
if request.method == 'POST':
if 'id' in request.POST and str(survey.id) == request.POST['id']:
form = Delete_Eng_Survey_Form(request.POST, instance=survey)
if form.is_valid():
survey.delete()
messages.add_message(request,
messages.SUCCESS,
'Survey and relationships removed.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('survey'))
add_breadcrumb(title="Delete Survey", top_level=False, request=request)
return render(request, 'defectDojo-engagement-survey/delete_survey.html',
{'survey': survey,
'form': form,
'rels': rels,
})
示例4: viewmap_delete_page
def viewmap_delete_page(request, vsid):
page = get_object_or_404(Page, pk=vsid)
uim = page.uimodel
if uim.is_frozen:
return render(request, 'mcms/uimodels/frozen.html', dict(uimodel=uim))
collector = NestedObjects(using='default')
collector.collect([page])
to_delete = collector.nested()
if request.method == 'POST':
page.delete()
return HttpResponseRedirect(reverse('mcms:uimodels:edit_viewmap',
kwargs={'vmid': page.viewmap.id}))
opts = page._meta
object_name = force_unicode(opts.verbose_name)
title = ('Are you sure?')
context = {
'title': title,
'object_name': object_name,
'object': page,
'deleted_objects': to_delete,
'opts': opts,
'app_label': opts.app_label,
}
return TemplateResponse(
request,
'mcms/uimodels/delete_confirmation.html', context, current_app='Test')
示例5: get_context_data
def get_context_data(self, *args, **kwargs):
context = super(DeleteView, self).get_context_data(*args, **kwargs)
using = router.db_for_write(self.model)
collector = NestedObjects(using=using)
collector.collect([self.object])
context["related_objects"] = collector.nested()
return context
示例6: deletion_tree
def deletion_tree(obj):
''' Return a list of all nested objects that will be deleted '''
collector = NestedObjects(using=obj._state.db)
collector.collect([obj])
def format_callback(obj):
return u'%s: %s' % (force_text(obj._meta.verbose_name), force_text(obj))
return collector.nested(format_callback)
示例7: hand_clean_DELETE
def hand_clean_DELETE(self):
"""
We don't validate the 'DELETE' field itself because on
templates it's not rendered using the field information, but
just using a generic "deletion_field" of the InlineModelAdmin.
"""
if self.cleaned_data.get(DELETION_FIELD_NAME, False):
collector = NestedObjects()
collector.collect([self.instance])
if collector.protected:
objs = []
for p in collector.protected:
objs.append(
# Translators: Model verbose name and instance representation, suitable to be an item in a list
_('%(class_name)s %(instance)s') % {
'class_name': p._meta.verbose_name,
'instance': p}
)
params = {'class_name': self._meta.model._meta.verbose_name,
'instance': self.instance,
'related_objects': get_text_list(objs, _('and'))}
msg = _("Deleting %(class_name)s %(instance)s would require "
"deleting the following protected related objects: "
"%(related_objects)s")
raise ValidationError(msg, code='deleting_protected', params=params)
示例8: get_related_objects
def get_related_objects( obj, to_update=DEFAULT_TO_UPDATE ):
collector = NestedObjects( using=DEFAULT_DB_ALIAS )
collector.collect( obj )
perms_needed = set()
def format_callback( o ):
opts = o._meta
key = '%s_%s' % ( opts.app_label, opts.object_name.lower() )
to_delete = key not in to_update
try:
admin_url = reverse( 'admin:%s_%s_change' % ( opts.app_label, opts.object_name.lower() ),
None, ( o._get_pk_val() ,) )
except:
return mark_safe( u'%s%s: %s%s' % ( '<strike>' if to_delete else '', capfirst( opts.verbose_name ), force_unicode( o ), '</strike>' if to_delete else '' ) )
try:
name = escape( str( o ) )
except Exception, e:
print e
name = 'None'
return mark_safe( u'%s%s: <a href="%s">%s</a>%s' %
( '<strike>' if to_delete else '', escape( capfirst( opts.verbose_name ) ),
admin_url, name, '</strike>' if to_delete else '' ) )
示例9: delete_engagement
def delete_engagement(request, eid):
engagement = get_object_or_404(Engagement, pk=eid)
product = engagement.product
form = DeleteEngagementForm(instance=engagement)
from django.contrib.admin.util import NestedObjects
from django.db import DEFAULT_DB_ALIAS
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([engagement])
rels = collector.nested()
if request.method == 'POST':
if 'id' in request.POST and str(engagement.id) == request.POST['id']:
form = DeleteEngagementForm(request.POST, instance=engagement)
if form.is_valid():
engagement.delete()
messages.add_message(request,
messages.SUCCESS,
'Engagement and relationships removed.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('view_product', args=(product.id,)))
add_breadcrumb(parent=engagement, title="Delete", top_level=False, request=request)
return render(request, 'dojo/delete_engagement.html',
{'engagement': engagement,
'form': form,
'rels': rels,
})
示例10: delete_user
def delete_user(request, uid):
user = get_object_or_404(Dojo_User, id=uid)
form = DeleteUserForm(instance=user)
from django.contrib.admin.util import NestedObjects
from django.db import DEFAULT_DB_ALIAS
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([user])
rels = collector.nested()
if user.id == request.user.id:
messages.add_message(request,
messages.ERROR,
'You may not delete yourself.',
extra_tags='alert-danger')
return HttpResponseRedirect(reverse('edit_user', args=(user.id,)))
if request.method == 'POST':
if 'id' in request.POST and str(user.id) == request.POST['id']:
form = DeleteUserForm(request.POST, instance=user)
if form.is_valid():
user.delete()
messages.add_message(request,
messages.SUCCESS,
'User and relationships removed.',
extra_tags='alert-success')
return HttpResponseRedirect(reverse('users'))
add_breadcrumb(title="Delete User", top_level=False, request=request)
return render(request, 'dojo/delete_user.html',
{'to_delete': user,
'form': form,
'rels': rels,
})
示例11: get_related_objects
def get_related_objects(self, flatten=False):
"""
Returns all objects related to the current.
"""
collector = NestedObjects(using='default')
collector.collect([self])
if flatten:
return list(utils.flatten(collector.nested()))
return collector.nested()
示例12: list_deleted_objects
def list_deleted_objects(obj):
model = obj.__class__
def format_callback(item):
return u'%s: %s' % (item._meta.verbose_name.capitalize(), force_unicode(item))
collector = NestedObjects(using=router.db_for_write(model))
collector.collect(model.objects.filter(id=obj.id))
to_delete = collector.nested(format_callback)
return {'to_delete': to_delete}
示例13: test_on_delete_do_nothing
def test_on_delete_do_nothing(self):
"""
Check that the nested collector doesn't query for DO_NOTHING objects.
"""
n = NestedObjects(using=DEFAULT_DB_ALIAS)
objs = [Event.objects.create()]
EventGuide.objects.create(event=objs[0])
with self.assertNumQueries(2):
# One for Location, one for Guest, and no query for EventGuide
n.collect(objs)
示例14: deepcopy
def deepcopy(self, newname, value=None, field=None, duplicate_order=None):
"""
Duplicate all related objects of obj setting
field to value. If one of the duplicate
objects has an FK to another duplicate object
update that as well. Return the duplicate copy
of obj.
duplicate_order is a list of models which specify how
the duplicate objects are saved. For complex objects
this can matter. Check to save if objects are being
saved correctly and if not just pass in related objects
in the order that they should be saved.
"""
obj = self
collector = NestedObjects(using='default')
collector.collect([obj])
collector.sort()
related_models = collector.data.keys()
data_snapshot = {}
for key in collector.data.keys():
data_snapshot.update({ key: dict(zip([item.pk for item in collector.data[key]], [item for item in collector.data[key]])) })
root_obj = None
# Sometimes it's good enough just to save in reverse deletion order.
if duplicate_order is None:
duplicate_order = reversed(related_models)
for model in duplicate_order:
# Find all FKs on model that point to a related_model.
fks = []
for f in model._meta.fields:
if isinstance(f, ForeignKey) and f.rel.to in related_models:
fks.append(f)
# Replace each `sub_obj` with a duplicate.
if model not in collector.data:
continue
sub_objects = collector.data[model]
for obj in sub_objects:
for fk in fks:
fk_value = getattr(obj, "%s_id" % fk.name)
# If this FK has been duplicated then point to the duplicate.
fk_rel_to = data_snapshot[fk.rel.to]
if fk_value in fk_rel_to:
dupe_obj = fk_rel_to[fk_value]
setattr(obj, fk.name, dupe_obj)
# Duplicate the object and save it.
obj.id = None
if field is not None:
setattr(obj, field, value)
obj.save()
if root_obj is None:
root_obj = obj
setattr(root_obj, 'name', newname)
return root_obj
示例15: make_mobile_numbers_unique
def make_mobile_numbers_unique(users):
for user in users:
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([user])
items = collector.nested()
for item in items:
if isinstance(item, User):
continue
else:
unique_instances = set([str(instance.__class__.__name__) for instance in item])
if len(unique_instances) == 1:
pass