Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
BaseModelAdmin.get_ordering | (self, request) |
Hook for specifying field ordering.
|
Hook for specifying field ordering.
| def get_ordering(self, request):
"""
Hook for specifying field ordering.
"""
return self.ordering or () | [
"def",
"get_ordering",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"ordering",
"or",
"(",
")"
] | [
342,
4
] | [
346,
34
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_readonly_fields | (self, request, obj=None) |
Hook for specifying custom readonly fields.
|
Hook for specifying custom readonly fields.
| def get_readonly_fields(self, request, obj=None):
"""
Hook for specifying custom readonly fields.
"""
return self.readonly_fields | [
"def",
"get_readonly_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"self",
".",
"readonly_fields"
] | [
348,
4
] | [
352,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_prepopulated_fields | (self, request, obj=None) |
Hook for specifying custom prepopulated fields.
|
Hook for specifying custom prepopulated fields.
| def get_prepopulated_fields(self, request, obj=None):
"""
Hook for specifying custom prepopulated fields.
"""
return self.prepopulated_fields | [
"def",
"get_prepopulated_fields",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"self",
".",
"prepopulated_fields"
] | [
354,
4
] | [
358,
39
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_queryset | (self, request) |
Return a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
|
Return a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
| def get_queryset(self, request):
"""
Return a QuerySet of all model instances that can be edited by the
admin site. This is used by changelist_view.
"""
qs = self.model._default_manager.get_queryset()
# TODO: this should be handled by some parameter to the ChangeList.
ordering = self.get_ordering(request)
if ordering:
qs = qs.order_by(*ordering)
return qs | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"qs",
"=",
"self",
".",
"model",
".",
"_default_manager",
".",
"get_queryset",
"(",
")",
"# TODO: this should be handled by some parameter to the ChangeList.",
"ordering",
"=",
"self",
".",
"get_ordering",
"(",
"request",
")",
"if",
"ordering",
":",
"qs",
"=",
"qs",
".",
"order_by",
"(",
"*",
"ordering",
")",
"return",
"qs"
] | [
360,
4
] | [
370,
17
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.get_sortable_by | (self, request) | Hook for specifying which fields can be sorted in the changelist. | Hook for specifying which fields can be sorted in the changelist. | def get_sortable_by(self, request):
"""Hook for specifying which fields can be sorted in the changelist."""
return self.sortable_by if self.sortable_by is not None else self.get_list_display(request) | [
"def",
"get_sortable_by",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"sortable_by",
"if",
"self",
".",
"sortable_by",
"is",
"not",
"None",
"else",
"self",
".",
"get_list_display",
"(",
"request",
")"
] | [
372,
4
] | [
374,
99
] | python | en | ['en', 'en', 'en'] | True |
BaseModelAdmin.to_field_allowed | (self, request, to_field) |
Return True if the model associated with this admin should be
allowed to be referenced by the specified field.
|
Return True if the model associated with this admin should be
allowed to be referenced by the specified field.
| def to_field_allowed(self, request, to_field):
"""
Return True if the model associated with this admin should be
allowed to be referenced by the specified field.
"""
opts = self.model._meta
try:
field = opts.get_field(to_field)
except FieldDoesNotExist:
return False
# Always allow referencing the primary key since it's already possible
# to get this information from the change view URL.
if field.primary_key:
return True
# Allow reverse relationships to models defining m2m fields if they
# target the specified field.
for many_to_many in opts.many_to_many:
if many_to_many.m2m_target_field_name() == to_field:
return True
# Make sure at least one of the models registered for this site
# references this field through a FK or a M2M relationship.
registered_models = set()
for model, admin in self.admin_site._registry.items():
registered_models.add(model)
for inline in admin.inlines:
registered_models.add(inline.model)
related_objects = (
f for f in opts.get_fields(include_hidden=True)
if (f.auto_created and not f.concrete)
)
for related_object in related_objects:
related_model = related_object.related_model
remote_field = related_object.field.remote_field
if (any(issubclass(model, related_model) for model in registered_models) and
hasattr(remote_field, 'get_related_field') and
remote_field.get_related_field() == field):
return True
return False | [
"def",
"to_field_allowed",
"(",
"self",
",",
"request",
",",
"to_field",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"try",
":",
"field",
"=",
"opts",
".",
"get_field",
"(",
"to_field",
")",
"except",
"FieldDoesNotExist",
":",
"return",
"False",
"# Always allow referencing the primary key since it's already possible",
"# to get this information from the change view URL.",
"if",
"field",
".",
"primary_key",
":",
"return",
"True",
"# Allow reverse relationships to models defining m2m fields if they",
"# target the specified field.",
"for",
"many_to_many",
"in",
"opts",
".",
"many_to_many",
":",
"if",
"many_to_many",
".",
"m2m_target_field_name",
"(",
")",
"==",
"to_field",
":",
"return",
"True",
"# Make sure at least one of the models registered for this site",
"# references this field through a FK or a M2M relationship.",
"registered_models",
"=",
"set",
"(",
")",
"for",
"model",
",",
"admin",
"in",
"self",
".",
"admin_site",
".",
"_registry",
".",
"items",
"(",
")",
":",
"registered_models",
".",
"add",
"(",
"model",
")",
"for",
"inline",
"in",
"admin",
".",
"inlines",
":",
"registered_models",
".",
"add",
"(",
"inline",
".",
"model",
")",
"related_objects",
"=",
"(",
"f",
"for",
"f",
"in",
"opts",
".",
"get_fields",
"(",
"include_hidden",
"=",
"True",
")",
"if",
"(",
"f",
".",
"auto_created",
"and",
"not",
"f",
".",
"concrete",
")",
")",
"for",
"related_object",
"in",
"related_objects",
":",
"related_model",
"=",
"related_object",
".",
"related_model",
"remote_field",
"=",
"related_object",
".",
"field",
".",
"remote_field",
"if",
"(",
"any",
"(",
"issubclass",
"(",
"model",
",",
"related_model",
")",
"for",
"model",
"in",
"registered_models",
")",
"and",
"hasattr",
"(",
"remote_field",
",",
"'get_related_field'",
")",
"and",
"remote_field",
".",
"get_related_field",
"(",
")",
"==",
"field",
")",
":",
"return",
"True",
"return",
"False"
] | [
430,
4
] | [
473,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.has_add_permission | (self, request) |
Return True if the given request has permission to add an object.
Can be overridden by the user in subclasses.
|
Return True if the given request has permission to add an object.
Can be overridden by the user in subclasses.
| def has_add_permission(self, request):
"""
Return True if the given request has permission to add an object.
Can be overridden by the user in subclasses.
"""
opts = self.opts
codename = get_permission_codename('add', opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename)) | [
"def",
"has_add_permission",
"(",
"self",
",",
"request",
")",
":",
"opts",
"=",
"self",
".",
"opts",
"codename",
"=",
"get_permission_codename",
"(",
"'add'",
",",
"opts",
")",
"return",
"request",
".",
"user",
".",
"has_perm",
"(",
"\"%s.%s\"",
"%",
"(",
"opts",
".",
"app_label",
",",
"codename",
")",
")"
] | [
475,
4
] | [
482,
74
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.has_change_permission | (self, request, obj=None) |
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
|
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter. | def has_change_permission(self, request, obj=None):
"""
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to change the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to change *any* object of the given type.
"""
opts = self.opts
codename = get_permission_codename('change', opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename)) | [
"def",
"has_change_permission",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"opts",
"=",
"self",
".",
"opts",
"codename",
"=",
"get_permission_codename",
"(",
"'change'",
",",
"opts",
")",
"return",
"request",
".",
"user",
".",
"has_perm",
"(",
"\"%s.%s\"",
"%",
"(",
"opts",
".",
"app_label",
",",
"codename",
")",
")"
] | [
484,
4
] | [
497,
74
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.has_delete_permission | (self, request, obj=None) |
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
|
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter. | def has_delete_permission(self, request, obj=None):
"""
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if the given
request has permission to delete *any* object of the given type.
"""
opts = self.opts
codename = get_permission_codename('delete', opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename)) | [
"def",
"has_delete_permission",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"opts",
"=",
"self",
".",
"opts",
"codename",
"=",
"get_permission_codename",
"(",
"'delete'",
",",
"opts",
")",
"return",
"request",
".",
"user",
".",
"has_perm",
"(",
"\"%s.%s\"",
"%",
"(",
"opts",
".",
"app_label",
",",
"codename",
")",
")"
] | [
499,
4
] | [
512,
74
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.has_view_permission | (self, request, obj=None) |
Return True if the given request has permission to view the given
Django model instance. The default implementation doesn't examine the
`obj` parameter.
If overridden by the user in subclasses, it should return True if the
given request has permission to view the `obj` model instance. If `obj`
is None, it should return True if the request has permission to view
any object of the given type.
|
Return True if the given request has permission to view the given
Django model instance. The default implementation doesn't examine the
`obj` parameter. | def has_view_permission(self, request, obj=None):
"""
Return True if the given request has permission to view the given
Django model instance. The default implementation doesn't examine the
`obj` parameter.
If overridden by the user in subclasses, it should return True if the
given request has permission to view the `obj` model instance. If `obj`
is None, it should return True if the request has permission to view
any object of the given type.
"""
opts = self.opts
codename_view = get_permission_codename('view', opts)
codename_change = get_permission_codename('change', opts)
return (
request.user.has_perm('%s.%s' % (opts.app_label, codename_view)) or
request.user.has_perm('%s.%s' % (opts.app_label, codename_change))
) | [
"def",
"has_view_permission",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"opts",
"=",
"self",
".",
"opts",
"codename_view",
"=",
"get_permission_codename",
"(",
"'view'",
",",
"opts",
")",
"codename_change",
"=",
"get_permission_codename",
"(",
"'change'",
",",
"opts",
")",
"return",
"(",
"request",
".",
"user",
".",
"has_perm",
"(",
"'%s.%s'",
"%",
"(",
"opts",
".",
"app_label",
",",
"codename_view",
")",
")",
"or",
"request",
".",
"user",
".",
"has_perm",
"(",
"'%s.%s'",
"%",
"(",
"opts",
".",
"app_label",
",",
"codename_change",
")",
")",
")"
] | [
514,
4
] | [
531,
9
] | python | en | ['en', 'error', 'th'] | False |
BaseModelAdmin.has_module_permission | (self, request) |
Return True if the given request has any permission in the given
app label.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to view the module on
the admin index page and access the module's index page. Overriding it
does not restrict access to the add, change or delete views. Use
`ModelAdmin.has_(add|change|delete)_permission` for that.
|
Return True if the given request has any permission in the given
app label. | def has_module_permission(self, request):
"""
Return True if the given request has any permission in the given
app label.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to view the module on
the admin index page and access the module's index page. Overriding it
does not restrict access to the add, change or delete views. Use
`ModelAdmin.has_(add|change|delete)_permission` for that.
"""
return request.user.has_module_perms(self.opts.app_label) | [
"def",
"has_module_permission",
"(",
"self",
",",
"request",
")",
":",
"return",
"request",
".",
"user",
".",
"has_module_perms",
"(",
"self",
".",
"opts",
".",
"app_label",
")"
] | [
536,
4
] | [
547,
65
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_model_perms | (self, request) |
Return a dict of all perms for this model. This dict has the keys
``add``, ``change``, ``delete``, and ``view`` mapping to the True/False
for each of those actions.
|
Return a dict of all perms for this model. This dict has the keys
``add``, ``change``, ``delete``, and ``view`` mapping to the True/False
for each of those actions.
| def get_model_perms(self, request):
"""
Return a dict of all perms for this model. This dict has the keys
``add``, ``change``, ``delete``, and ``view`` mapping to the True/False
for each of those actions.
"""
return {
'add': self.has_add_permission(request),
'change': self.has_change_permission(request),
'delete': self.has_delete_permission(request),
'view': self.has_view_permission(request),
} | [
"def",
"get_model_perms",
"(",
"self",
",",
"request",
")",
":",
"return",
"{",
"'add'",
":",
"self",
".",
"has_add_permission",
"(",
"request",
")",
",",
"'change'",
":",
"self",
".",
"has_change_permission",
"(",
"request",
")",
",",
"'delete'",
":",
"self",
".",
"has_delete_permission",
"(",
"request",
")",
",",
"'view'",
":",
"self",
".",
"has_view_permission",
"(",
"request",
")",
",",
"}"
] | [
652,
4
] | [
663,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_form | (self, request, obj=None, change=False, **kwargs) |
Return a Form class for use in the admin add view. This is used by
add_view and change_view.
|
Return a Form class for use in the admin add view. This is used by
add_view and change_view.
| def get_form(self, request, obj=None, change=False, **kwargs):
"""
Return a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
if 'fields' in kwargs:
fields = kwargs.pop('fields')
else:
fields = flatten_fieldsets(self.get_fieldsets(request, obj))
excluded = self.get_exclude(request, obj)
exclude = [] if excluded is None else list(excluded)
readonly_fields = self.get_readonly_fields(request, obj)
exclude.extend(readonly_fields)
# Exclude all fields if it's a change form and the user doesn't have
# the change permission.
if change and hasattr(request, 'user') and not self.has_change_permission(request, obj):
exclude.extend(fields)
if excluded is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# ModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# if exclude is an empty list we pass None to be consistent with the
# default on modelform_factory
exclude = exclude or None
# Remove declared form fields which are in readonly_fields.
new_attrs = dict.fromkeys(f for f in readonly_fields if f in self.form.declared_fields)
form = type(self.form.__name__, (self.form,), new_attrs)
defaults = {
'form': form,
'fields': fields,
'exclude': exclude,
'formfield_callback': partial(self.formfield_for_dbfield, request=request),
**kwargs,
}
if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
defaults['fields'] = forms.ALL_FIELDS
try:
return modelform_factory(self.model, **defaults)
except FieldError as e:
raise FieldError(
'%s. Check fields/fieldsets/exclude attributes of class %s.'
% (e, self.__class__.__name__)
) | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"change",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'fields'",
"in",
"kwargs",
":",
"fields",
"=",
"kwargs",
".",
"pop",
"(",
"'fields'",
")",
"else",
":",
"fields",
"=",
"flatten_fieldsets",
"(",
"self",
".",
"get_fieldsets",
"(",
"request",
",",
"obj",
")",
")",
"excluded",
"=",
"self",
".",
"get_exclude",
"(",
"request",
",",
"obj",
")",
"exclude",
"=",
"[",
"]",
"if",
"excluded",
"is",
"None",
"else",
"list",
"(",
"excluded",
")",
"readonly_fields",
"=",
"self",
".",
"get_readonly_fields",
"(",
"request",
",",
"obj",
")",
"exclude",
".",
"extend",
"(",
"readonly_fields",
")",
"# Exclude all fields if it's a change form and the user doesn't have",
"# the change permission.",
"if",
"change",
"and",
"hasattr",
"(",
"request",
",",
"'user'",
")",
"and",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
")",
":",
"exclude",
".",
"extend",
"(",
"fields",
")",
"if",
"excluded",
"is",
"None",
"and",
"hasattr",
"(",
"self",
".",
"form",
",",
"'_meta'",
")",
"and",
"self",
".",
"form",
".",
"_meta",
".",
"exclude",
":",
"# Take the custom ModelForm's Meta.exclude into account only if the",
"# ModelAdmin doesn't define its own.",
"exclude",
".",
"extend",
"(",
"self",
".",
"form",
".",
"_meta",
".",
"exclude",
")",
"# if exclude is an empty list we pass None to be consistent with the",
"# default on modelform_factory",
"exclude",
"=",
"exclude",
"or",
"None",
"# Remove declared form fields which are in readonly_fields.",
"new_attrs",
"=",
"dict",
".",
"fromkeys",
"(",
"f",
"for",
"f",
"in",
"readonly_fields",
"if",
"f",
"in",
"self",
".",
"form",
".",
"declared_fields",
")",
"form",
"=",
"type",
"(",
"self",
".",
"form",
".",
"__name__",
",",
"(",
"self",
".",
"form",
",",
")",
",",
"new_attrs",
")",
"defaults",
"=",
"{",
"'form'",
":",
"form",
",",
"'fields'",
":",
"fields",
",",
"'exclude'",
":",
"exclude",
",",
"'formfield_callback'",
":",
"partial",
"(",
"self",
".",
"formfield_for_dbfield",
",",
"request",
"=",
"request",
")",
",",
"*",
"*",
"kwargs",
",",
"}",
"if",
"defaults",
"[",
"'fields'",
"]",
"is",
"None",
"and",
"not",
"modelform_defines_fields",
"(",
"defaults",
"[",
"'form'",
"]",
")",
":",
"defaults",
"[",
"'fields'",
"]",
"=",
"forms",
".",
"ALL_FIELDS",
"try",
":",
"return",
"modelform_factory",
"(",
"self",
".",
"model",
",",
"*",
"*",
"defaults",
")",
"except",
"FieldError",
"as",
"e",
":",
"raise",
"FieldError",
"(",
"'%s. Check fields/fieldsets/exclude attributes of class %s.'",
"%",
"(",
"e",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")"
] | [
668,
4
] | [
714,
13
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_changelist | (self, request, **kwargs) |
Return the ChangeList class for use on the changelist page.
|
Return the ChangeList class for use on the changelist page.
| def get_changelist(self, request, **kwargs):
"""
Return the ChangeList class for use on the changelist page.
"""
from django.contrib.admin.views.main import ChangeList
return ChangeList | [
"def",
"get_changelist",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"views",
".",
"main",
"import",
"ChangeList",
"return",
"ChangeList"
] | [
716,
4
] | [
721,
25
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_changelist_instance | (self, request) |
Return a `ChangeList` instance based on `request`. May raise
`IncorrectLookupParameters`.
|
Return a `ChangeList` instance based on `request`. May raise
`IncorrectLookupParameters`.
| def get_changelist_instance(self, request):
"""
Return a `ChangeList` instance based on `request`. May raise
`IncorrectLookupParameters`.
"""
list_display = self.get_list_display(request)
list_display_links = self.get_list_display_links(request, list_display)
# Add the action checkboxes if any actions are available.
if self.get_actions(request):
list_display = ['action_checkbox', *list_display]
sortable_by = self.get_sortable_by(request)
ChangeList = self.get_changelist(request)
return ChangeList(
request,
self.model,
list_display,
list_display_links,
self.get_list_filter(request),
self.date_hierarchy,
self.get_search_fields(request),
self.get_list_select_related(request),
self.list_per_page,
self.list_max_show_all,
self.list_editable,
self,
sortable_by,
) | [
"def",
"get_changelist_instance",
"(",
"self",
",",
"request",
")",
":",
"list_display",
"=",
"self",
".",
"get_list_display",
"(",
"request",
")",
"list_display_links",
"=",
"self",
".",
"get_list_display_links",
"(",
"request",
",",
"list_display",
")",
"# Add the action checkboxes if any actions are available.",
"if",
"self",
".",
"get_actions",
"(",
"request",
")",
":",
"list_display",
"=",
"[",
"'action_checkbox'",
",",
"*",
"list_display",
"]",
"sortable_by",
"=",
"self",
".",
"get_sortable_by",
"(",
"request",
")",
"ChangeList",
"=",
"self",
".",
"get_changelist",
"(",
"request",
")",
"return",
"ChangeList",
"(",
"request",
",",
"self",
".",
"model",
",",
"list_display",
",",
"list_display_links",
",",
"self",
".",
"get_list_filter",
"(",
"request",
")",
",",
"self",
".",
"date_hierarchy",
",",
"self",
".",
"get_search_fields",
"(",
"request",
")",
",",
"self",
".",
"get_list_select_related",
"(",
"request",
")",
",",
"self",
".",
"list_per_page",
",",
"self",
".",
"list_max_show_all",
",",
"self",
".",
"list_editable",
",",
"self",
",",
"sortable_by",
",",
")"
] | [
723,
4
] | [
749,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_object | (self, request, object_id, from_field=None) |
Return an instance matching the field and value provided, the primary
key is used if no field is provided. Return ``None`` if no match is
found or the object_id fails validation.
|
Return an instance matching the field and value provided, the primary
key is used if no field is provided. Return ``None`` if no match is
found or the object_id fails validation.
| def get_object(self, request, object_id, from_field=None):
"""
Return an instance matching the field and value provided, the primary
key is used if no field is provided. Return ``None`` if no match is
found or the object_id fails validation.
"""
queryset = self.get_queryset(request)
model = queryset.model
field = model._meta.pk if from_field is None else model._meta.get_field(from_field)
try:
object_id = field.to_python(object_id)
return queryset.get(**{field.name: object_id})
except (model.DoesNotExist, ValidationError, ValueError):
return None | [
"def",
"get_object",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"from_field",
"=",
"None",
")",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
"request",
")",
"model",
"=",
"queryset",
".",
"model",
"field",
"=",
"model",
".",
"_meta",
".",
"pk",
"if",
"from_field",
"is",
"None",
"else",
"model",
".",
"_meta",
".",
"get_field",
"(",
"from_field",
")",
"try",
":",
"object_id",
"=",
"field",
".",
"to_python",
"(",
"object_id",
")",
"return",
"queryset",
".",
"get",
"(",
"*",
"*",
"{",
"field",
".",
"name",
":",
"object_id",
"}",
")",
"except",
"(",
"model",
".",
"DoesNotExist",
",",
"ValidationError",
",",
"ValueError",
")",
":",
"return",
"None"
] | [
751,
4
] | [
764,
23
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_changelist_form | (self, request, **kwargs) |
Return a Form class for use in the Formset on the changelist page.
|
Return a Form class for use in the Formset on the changelist page.
| def get_changelist_form(self, request, **kwargs):
"""
Return a Form class for use in the Formset on the changelist page.
"""
defaults = {
'formfield_callback': partial(self.formfield_for_dbfield, request=request),
**kwargs,
}
if defaults.get('fields') is None and not modelform_defines_fields(defaults.get('form')):
defaults['fields'] = forms.ALL_FIELDS
return modelform_factory(self.model, **defaults) | [
"def",
"get_changelist_form",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'formfield_callback'",
":",
"partial",
"(",
"self",
".",
"formfield_for_dbfield",
",",
"request",
"=",
"request",
")",
",",
"*",
"*",
"kwargs",
",",
"}",
"if",
"defaults",
".",
"get",
"(",
"'fields'",
")",
"is",
"None",
"and",
"not",
"modelform_defines_fields",
"(",
"defaults",
".",
"get",
"(",
"'form'",
")",
")",
":",
"defaults",
"[",
"'fields'",
"]",
"=",
"forms",
".",
"ALL_FIELDS",
"return",
"modelform_factory",
"(",
"self",
".",
"model",
",",
"*",
"*",
"defaults",
")"
] | [
766,
4
] | [
777,
56
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_changelist_formset | (self, request, **kwargs) |
Return a FormSet class for use on the changelist page if list_editable
is used.
|
Return a FormSet class for use on the changelist page if list_editable
is used.
| def get_changelist_formset(self, request, **kwargs):
"""
Return a FormSet class for use on the changelist page if list_editable
is used.
"""
defaults = {
'formfield_callback': partial(self.formfield_for_dbfield, request=request),
**kwargs,
}
return modelformset_factory(
self.model, self.get_changelist_form(request), extra=0,
fields=self.list_editable, **defaults
) | [
"def",
"get_changelist_formset",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'formfield_callback'",
":",
"partial",
"(",
"self",
".",
"formfield_for_dbfield",
",",
"request",
"=",
"request",
")",
",",
"*",
"*",
"kwargs",
",",
"}",
"return",
"modelformset_factory",
"(",
"self",
".",
"model",
",",
"self",
".",
"get_changelist_form",
"(",
"request",
")",
",",
"extra",
"=",
"0",
",",
"fields",
"=",
"self",
".",
"list_editable",
",",
"*",
"*",
"defaults",
")"
] | [
779,
4
] | [
791,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_formsets_with_inlines | (self, request, obj=None) |
Yield formsets and the corresponding inlines.
|
Yield formsets and the corresponding inlines.
| def get_formsets_with_inlines(self, request, obj=None):
"""
Yield formsets and the corresponding inlines.
"""
for inline in self.get_inline_instances(request, obj):
yield inline.get_formset(request, obj), inline | [
"def",
"get_formsets_with_inlines",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"for",
"inline",
"in",
"self",
".",
"get_inline_instances",
"(",
"request",
",",
"obj",
")",
":",
"yield",
"inline",
".",
"get_formset",
"(",
"request",
",",
"obj",
")",
",",
"inline"
] | [
793,
4
] | [
798,
58
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.log_addition | (self, request, object, message) |
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
|
Log that an object has been successfully added. | def log_addition(self, request, object, message):
"""
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import ADDITION, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
object_id=object.pk,
object_repr=str(object),
action_flag=ADDITION,
change_message=message,
) | [
"def",
"log_addition",
"(",
"self",
",",
"request",
",",
"object",
",",
"message",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"models",
"import",
"ADDITION",
",",
"LogEntry",
"return",
"LogEntry",
".",
"objects",
".",
"log_action",
"(",
"user_id",
"=",
"request",
".",
"user",
".",
"pk",
",",
"content_type_id",
"=",
"get_content_type_for_model",
"(",
"object",
")",
".",
"pk",
",",
"object_id",
"=",
"object",
".",
"pk",
",",
"object_repr",
"=",
"str",
"(",
"object",
")",
",",
"action_flag",
"=",
"ADDITION",
",",
"change_message",
"=",
"message",
",",
")"
] | [
803,
4
] | [
817,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.log_change | (self, request, object, message) |
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
|
Log that an object has been successfully changed. | def log_change(self, request, object, message):
"""
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import CHANGE, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
object_id=object.pk,
object_repr=str(object),
action_flag=CHANGE,
change_message=message,
) | [
"def",
"log_change",
"(",
"self",
",",
"request",
",",
"object",
",",
"message",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"models",
"import",
"CHANGE",
",",
"LogEntry",
"return",
"LogEntry",
".",
"objects",
".",
"log_action",
"(",
"user_id",
"=",
"request",
".",
"user",
".",
"pk",
",",
"content_type_id",
"=",
"get_content_type_for_model",
"(",
"object",
")",
".",
"pk",
",",
"object_id",
"=",
"object",
".",
"pk",
",",
"object_repr",
"=",
"str",
"(",
"object",
")",
",",
"action_flag",
"=",
"CHANGE",
",",
"change_message",
"=",
"message",
",",
")"
] | [
819,
4
] | [
833,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.log_deletion | (self, request, object, object_repr) |
Log that an object will be deleted. Note that this method must be
called before the deletion.
The default implementation creates an admin LogEntry object.
|
Log that an object will be deleted. Note that this method must be
called before the deletion. | def log_deletion(self, request, object, object_repr):
"""
Log that an object will be deleted. Note that this method must be
called before the deletion.
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import DELETION, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
object_id=object.pk,
object_repr=object_repr,
action_flag=DELETION,
) | [
"def",
"log_deletion",
"(",
"self",
",",
"request",
",",
"object",
",",
"object_repr",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"models",
"import",
"DELETION",
",",
"LogEntry",
"return",
"LogEntry",
".",
"objects",
".",
"log_action",
"(",
"user_id",
"=",
"request",
".",
"user",
".",
"pk",
",",
"content_type_id",
"=",
"get_content_type_for_model",
"(",
"object",
")",
".",
"pk",
",",
"object_id",
"=",
"object",
".",
"pk",
",",
"object_repr",
"=",
"object_repr",
",",
"action_flag",
"=",
"DELETION",
",",
")"
] | [
835,
4
] | [
849,
9
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.action_checkbox | (self, obj) |
A list_display column containing a checkbox widget.
|
A list_display column containing a checkbox widget.
| def action_checkbox(self, obj):
"""
A list_display column containing a checkbox widget.
"""
return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, str(obj.pk)) | [
"def",
"action_checkbox",
"(",
"self",
",",
"obj",
")",
":",
"return",
"helpers",
".",
"checkbox",
".",
"render",
"(",
"helpers",
".",
"ACTION_CHECKBOX_NAME",
",",
"str",
"(",
"obj",
".",
"pk",
")",
")"
] | [
852,
4
] | [
856,
81
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin._get_base_actions | (self) | Return the list of actions, prior to any request-based filtering. | Return the list of actions, prior to any request-based filtering. | def _get_base_actions(self):
"""Return the list of actions, prior to any request-based filtering."""
actions = []
base_actions = (self.get_action(action) for action in self.actions or [])
# get_action might have returned None, so filter any of those out.
base_actions = [action for action in base_actions if action]
base_action_names = {name for _, name, _ in base_actions}
# Gather actions from the admin site first
for (name, func) in self.admin_site.actions:
if name in base_action_names:
continue
description = self._get_action_description(func, name)
actions.append((func, name, description))
# Add actions from this ModelAdmin.
actions.extend(base_actions)
return actions | [
"def",
"_get_base_actions",
"(",
"self",
")",
":",
"actions",
"=",
"[",
"]",
"base_actions",
"=",
"(",
"self",
".",
"get_action",
"(",
"action",
")",
"for",
"action",
"in",
"self",
".",
"actions",
"or",
"[",
"]",
")",
"# get_action might have returned None, so filter any of those out.",
"base_actions",
"=",
"[",
"action",
"for",
"action",
"in",
"base_actions",
"if",
"action",
"]",
"base_action_names",
"=",
"{",
"name",
"for",
"_",
",",
"name",
",",
"_",
"in",
"base_actions",
"}",
"# Gather actions from the admin site first",
"for",
"(",
"name",
",",
"func",
")",
"in",
"self",
".",
"admin_site",
".",
"actions",
":",
"if",
"name",
"in",
"base_action_names",
":",
"continue",
"description",
"=",
"self",
".",
"_get_action_description",
"(",
"func",
",",
"name",
")",
"actions",
".",
"append",
"(",
"(",
"func",
",",
"name",
",",
"description",
")",
")",
"# Add actions from this ModelAdmin.",
"actions",
".",
"extend",
"(",
"base_actions",
")",
"return",
"actions"
] | [
862,
4
] | [
878,
22
] | python | en | ['en', 'en', 'en'] | True |
ModelAdmin._filter_actions_by_permissions | (self, request, actions) | Filter out any actions that the user doesn't have access to. | Filter out any actions that the user doesn't have access to. | def _filter_actions_by_permissions(self, request, actions):
"""Filter out any actions that the user doesn't have access to."""
filtered_actions = []
for action in actions:
callable = action[0]
if not hasattr(callable, 'allowed_permissions'):
filtered_actions.append(action)
continue
permission_checks = (
getattr(self, 'has_%s_permission' % permission)
for permission in callable.allowed_permissions
)
if any(has_permission(request) for has_permission in permission_checks):
filtered_actions.append(action)
return filtered_actions | [
"def",
"_filter_actions_by_permissions",
"(",
"self",
",",
"request",
",",
"actions",
")",
":",
"filtered_actions",
"=",
"[",
"]",
"for",
"action",
"in",
"actions",
":",
"callable",
"=",
"action",
"[",
"0",
"]",
"if",
"not",
"hasattr",
"(",
"callable",
",",
"'allowed_permissions'",
")",
":",
"filtered_actions",
".",
"append",
"(",
"action",
")",
"continue",
"permission_checks",
"=",
"(",
"getattr",
"(",
"self",
",",
"'has_%s_permission'",
"%",
"permission",
")",
"for",
"permission",
"in",
"callable",
".",
"allowed_permissions",
")",
"if",
"any",
"(",
"has_permission",
"(",
"request",
")",
"for",
"has_permission",
"in",
"permission_checks",
")",
":",
"filtered_actions",
".",
"append",
"(",
"action",
")",
"return",
"filtered_actions"
] | [
880,
4
] | [
894,
31
] | python | en | ['en', 'en', 'en'] | True |
ModelAdmin.get_actions | (self, request) |
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
|
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
| def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is set to None that means actions are disabled on
# this page.
if self.actions is None or IS_POPUP_VAR in request.GET:
return {}
actions = self._filter_actions_by_permissions(request, self._get_base_actions())
return {name: (func, name, desc) for func, name, desc in actions} | [
"def",
"get_actions",
"(",
"self",
",",
"request",
")",
":",
"# If self.actions is set to None that means actions are disabled on",
"# this page.",
"if",
"self",
".",
"actions",
"is",
"None",
"or",
"IS_POPUP_VAR",
"in",
"request",
".",
"GET",
":",
"return",
"{",
"}",
"actions",
"=",
"self",
".",
"_filter_actions_by_permissions",
"(",
"request",
",",
"self",
".",
"_get_base_actions",
"(",
")",
")",
"return",
"{",
"name",
":",
"(",
"func",
",",
"name",
",",
"desc",
")",
"for",
"func",
",",
"name",
",",
"desc",
"in",
"actions",
"}"
] | [
896,
4
] | [
906,
73
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_action_choices | (self, request, default_choices=models.BLANK_CHOICE_DASH) |
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
|
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
| def get_action_choices(self, request, default_choices=models.BLANK_CHOICE_DASH):
"""
Return a list of choices for use in a form object. Each choice is a
tuple (name, description).
"""
choices = [] + default_choices
for func, name, description in self.get_actions(request).values():
choice = (name, description % model_format_dict(self.opts))
choices.append(choice)
return choices | [
"def",
"get_action_choices",
"(",
"self",
",",
"request",
",",
"default_choices",
"=",
"models",
".",
"BLANK_CHOICE_DASH",
")",
":",
"choices",
"=",
"[",
"]",
"+",
"default_choices",
"for",
"func",
",",
"name",
",",
"description",
"in",
"self",
".",
"get_actions",
"(",
"request",
")",
".",
"values",
"(",
")",
":",
"choice",
"=",
"(",
"name",
",",
"description",
"%",
"model_format_dict",
"(",
"self",
".",
"opts",
")",
")",
"choices",
".",
"append",
"(",
"choice",
")",
"return",
"choices"
] | [
908,
4
] | [
917,
22
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_action | (self, action) |
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
|
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
| def get_action(self, action):
"""
Return a given action from a parameter, which can either be a callable,
or the name of a method on the ModelAdmin. Return is a tuple of
(callable, name, description).
"""
# If the action is a callable, just use it.
if callable(action):
func = action
action = action.__name__
# Next, look for a method. Grab it off self.__class__ to get an unbound
# method instead of a bound one; this ensures that the calling
# conventions are the same for functions and methods.
elif hasattr(self.__class__, action):
func = getattr(self.__class__, action)
# Finally, look for a named method on the admin site
else:
try:
func = self.admin_site.get_action(action)
except KeyError:
return None
description = self._get_action_description(func, action)
return func, action, description | [
"def",
"get_action",
"(",
"self",
",",
"action",
")",
":",
"# If the action is a callable, just use it.",
"if",
"callable",
"(",
"action",
")",
":",
"func",
"=",
"action",
"action",
"=",
"action",
".",
"__name__",
"# Next, look for a method. Grab it off self.__class__ to get an unbound",
"# method instead of a bound one; this ensures that the calling",
"# conventions are the same for functions and methods.",
"elif",
"hasattr",
"(",
"self",
".",
"__class__",
",",
"action",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
".",
"__class__",
",",
"action",
")",
"# Finally, look for a named method on the admin site",
"else",
":",
"try",
":",
"func",
"=",
"self",
".",
"admin_site",
".",
"get_action",
"(",
"action",
")",
"except",
"KeyError",
":",
"return",
"None",
"description",
"=",
"self",
".",
"_get_action_description",
"(",
"func",
",",
"action",
")",
"return",
"func",
",",
"action",
",",
"description"
] | [
919,
4
] | [
944,
40
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_list_display | (self, request) |
Return a sequence containing the fields to be displayed on the
changelist.
|
Return a sequence containing the fields to be displayed on the
changelist.
| def get_list_display(self, request):
"""
Return a sequence containing the fields to be displayed on the
changelist.
"""
return self.list_display | [
"def",
"get_list_display",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"list_display"
] | [
946,
4
] | [
951,
32
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_list_display_links | (self, request, list_display) |
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
|
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
| def get_list_display_links(self, request, list_display):
"""
Return a sequence containing the fields to be displayed as links
on the changelist. The list_display parameter is the list of fields
returned by get_list_display().
"""
if self.list_display_links or self.list_display_links is None or not list_display:
return self.list_display_links
else:
# Use only the first item in list_display as link
return list(list_display)[:1] | [
"def",
"get_list_display_links",
"(",
"self",
",",
"request",
",",
"list_display",
")",
":",
"if",
"self",
".",
"list_display_links",
"or",
"self",
".",
"list_display_links",
"is",
"None",
"or",
"not",
"list_display",
":",
"return",
"self",
".",
"list_display_links",
"else",
":",
"# Use only the first item in list_display as link",
"return",
"list",
"(",
"list_display",
")",
"[",
":",
"1",
"]"
] | [
953,
4
] | [
963,
41
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_list_filter | (self, request) |
Return a sequence containing the fields to be displayed as filters in
the right sidebar of the changelist page.
|
Return a sequence containing the fields to be displayed as filters in
the right sidebar of the changelist page.
| def get_list_filter(self, request):
"""
Return a sequence containing the fields to be displayed as filters in
the right sidebar of the changelist page.
"""
return self.list_filter | [
"def",
"get_list_filter",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"list_filter"
] | [
965,
4
] | [
970,
31
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_list_select_related | (self, request) |
Return a list of fields to add to the select_related() part of the
changelist items query.
|
Return a list of fields to add to the select_related() part of the
changelist items query.
| def get_list_select_related(self, request):
"""
Return a list of fields to add to the select_related() part of the
changelist items query.
"""
return self.list_select_related | [
"def",
"get_list_select_related",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"list_select_related"
] | [
972,
4
] | [
977,
39
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_search_fields | (self, request) |
Return a sequence containing the fields to be searched whenever
somebody submits a search query.
|
Return a sequence containing the fields to be searched whenever
somebody submits a search query.
| def get_search_fields(self, request):
"""
Return a sequence containing the fields to be searched whenever
somebody submits a search query.
"""
return self.search_fields | [
"def",
"get_search_fields",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"search_fields"
] | [
979,
4
] | [
984,
33
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_search_results | (self, request, queryset, search_term) |
Return a tuple containing a queryset to implement the search
and a boolean indicating if the results may contain duplicates.
|
Return a tuple containing a queryset to implement the search
and a boolean indicating if the results may contain duplicates.
| def get_search_results(self, request, queryset, search_term):
"""
Return a tuple containing a queryset to implement the search
and a boolean indicating if the results may contain duplicates.
"""
# Apply keyword searches.
def construct_search(field_name):
if field_name.startswith('^'):
return "%s__istartswith" % field_name[1:]
elif field_name.startswith('='):
return "%s__iexact" % field_name[1:]
elif field_name.startswith('@'):
return "%s__search" % field_name[1:]
# Use field_name if it includes a lookup.
opts = queryset.model._meta
lookup_fields = field_name.split(LOOKUP_SEP)
# Go through the fields, following all relations.
prev_field = None
for path_part in lookup_fields:
if path_part == 'pk':
path_part = opts.pk.name
try:
field = opts.get_field(path_part)
except FieldDoesNotExist:
# Use valid query lookups.
if prev_field and prev_field.get_lookup(path_part):
return field_name
else:
prev_field = field
if hasattr(field, 'get_path_info'):
# Update opts to follow the relation.
opts = field.get_path_info()[-1].to_opts
# Otherwise, use the field with icontains.
return "%s__icontains" % field_name
may_have_duplicates = False
search_fields = self.get_search_fields(request)
if search_fields and search_term:
orm_lookups = [construct_search(str(search_field))
for search_field in search_fields]
for bit in smart_split(search_term):
if bit.startswith(('"', "'")) and bit[0] == bit[-1]:
bit = unescape_string_literal(bit)
or_queries = [models.Q(**{orm_lookup: bit})
for orm_lookup in orm_lookups]
queryset = queryset.filter(reduce(operator.or_, or_queries))
may_have_duplicates |= any(
lookup_needs_distinct(self.opts, search_spec)
for search_spec in orm_lookups
)
return queryset, may_have_duplicates | [
"def",
"get_search_results",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"search_term",
")",
":",
"# Apply keyword searches.",
"def",
"construct_search",
"(",
"field_name",
")",
":",
"if",
"field_name",
".",
"startswith",
"(",
"'^'",
")",
":",
"return",
"\"%s__istartswith\"",
"%",
"field_name",
"[",
"1",
":",
"]",
"elif",
"field_name",
".",
"startswith",
"(",
"'='",
")",
":",
"return",
"\"%s__iexact\"",
"%",
"field_name",
"[",
"1",
":",
"]",
"elif",
"field_name",
".",
"startswith",
"(",
"'@'",
")",
":",
"return",
"\"%s__search\"",
"%",
"field_name",
"[",
"1",
":",
"]",
"# Use field_name if it includes a lookup.",
"opts",
"=",
"queryset",
".",
"model",
".",
"_meta",
"lookup_fields",
"=",
"field_name",
".",
"split",
"(",
"LOOKUP_SEP",
")",
"# Go through the fields, following all relations.",
"prev_field",
"=",
"None",
"for",
"path_part",
"in",
"lookup_fields",
":",
"if",
"path_part",
"==",
"'pk'",
":",
"path_part",
"=",
"opts",
".",
"pk",
".",
"name",
"try",
":",
"field",
"=",
"opts",
".",
"get_field",
"(",
"path_part",
")",
"except",
"FieldDoesNotExist",
":",
"# Use valid query lookups.",
"if",
"prev_field",
"and",
"prev_field",
".",
"get_lookup",
"(",
"path_part",
")",
":",
"return",
"field_name",
"else",
":",
"prev_field",
"=",
"field",
"if",
"hasattr",
"(",
"field",
",",
"'get_path_info'",
")",
":",
"# Update opts to follow the relation.",
"opts",
"=",
"field",
".",
"get_path_info",
"(",
")",
"[",
"-",
"1",
"]",
".",
"to_opts",
"# Otherwise, use the field with icontains.",
"return",
"\"%s__icontains\"",
"%",
"field_name",
"may_have_duplicates",
"=",
"False",
"search_fields",
"=",
"self",
".",
"get_search_fields",
"(",
"request",
")",
"if",
"search_fields",
"and",
"search_term",
":",
"orm_lookups",
"=",
"[",
"construct_search",
"(",
"str",
"(",
"search_field",
")",
")",
"for",
"search_field",
"in",
"search_fields",
"]",
"for",
"bit",
"in",
"smart_split",
"(",
"search_term",
")",
":",
"if",
"bit",
".",
"startswith",
"(",
"(",
"'\"'",
",",
"\"'\"",
")",
")",
"and",
"bit",
"[",
"0",
"]",
"==",
"bit",
"[",
"-",
"1",
"]",
":",
"bit",
"=",
"unescape_string_literal",
"(",
"bit",
")",
"or_queries",
"=",
"[",
"models",
".",
"Q",
"(",
"*",
"*",
"{",
"orm_lookup",
":",
"bit",
"}",
")",
"for",
"orm_lookup",
"in",
"orm_lookups",
"]",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"reduce",
"(",
"operator",
".",
"or_",
",",
"or_queries",
")",
")",
"may_have_duplicates",
"|=",
"any",
"(",
"lookup_needs_distinct",
"(",
"self",
".",
"opts",
",",
"search_spec",
")",
"for",
"search_spec",
"in",
"orm_lookups",
")",
"return",
"queryset",
",",
"may_have_duplicates"
] | [
986,
4
] | [
1036,
44
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_preserved_filters | (self, request) |
Return the preserved filters querystring.
|
Return the preserved filters querystring.
| def get_preserved_filters(self, request):
"""
Return the preserved filters querystring.
"""
match = request.resolver_match
if self.preserve_filters and match:
opts = self.model._meta
current_url = '%s:%s' % (match.app_name, match.url_name)
changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
if current_url == changelist_url:
preserved_filters = request.GET.urlencode()
else:
preserved_filters = request.GET.get('_changelist_filters')
if preserved_filters:
return urlencode({'_changelist_filters': preserved_filters})
return '' | [
"def",
"get_preserved_filters",
"(",
"self",
",",
"request",
")",
":",
"match",
"=",
"request",
".",
"resolver_match",
"if",
"self",
".",
"preserve_filters",
"and",
"match",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"current_url",
"=",
"'%s:%s'",
"%",
"(",
"match",
".",
"app_name",
",",
"match",
".",
"url_name",
")",
"changelist_url",
"=",
"'admin:%s_%s_changelist'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
"if",
"current_url",
"==",
"changelist_url",
":",
"preserved_filters",
"=",
"request",
".",
"GET",
".",
"urlencode",
"(",
")",
"else",
":",
"preserved_filters",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'_changelist_filters'",
")",
"if",
"preserved_filters",
":",
"return",
"urlencode",
"(",
"{",
"'_changelist_filters'",
":",
"preserved_filters",
"}",
")",
"return",
"''"
] | [
1038,
4
] | [
1054,
17
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.construct_change_message | (self, request, form, formsets, add=False) |
Construct a JSON structure describing changes from a changed object.
|
Construct a JSON structure describing changes from a changed object.
| def construct_change_message(self, request, form, formsets, add=False):
"""
Construct a JSON structure describing changes from a changed object.
"""
return construct_change_message(form, formsets, add) | [
"def",
"construct_change_message",
"(",
"self",
",",
"request",
",",
"form",
",",
"formsets",
",",
"add",
"=",
"False",
")",
":",
"return",
"construct_change_message",
"(",
"form",
",",
"formsets",
",",
"add",
")"
] | [
1056,
4
] | [
1060,
60
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.message_user | (self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False) |
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
|
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend. | def message_user(self, request, message, level=messages.INFO, extra_tags='',
fail_silently=False):
"""
Send a message to the user. The default implementation
posts a message using the django.contrib.messages backend.
Exposes almost the same API as messages.add_message(), but accepts the
positional arguments in a different order to maintain backwards
compatibility. For convenience, it accepts the `level` argument as
a string rather than the usual level number.
"""
if not isinstance(level, int):
# attempt to get the level if passed a string
try:
level = getattr(messages.constants, level.upper())
except AttributeError:
levels = messages.constants.DEFAULT_TAGS.values()
levels_repr = ', '.join('`%s`' % level for level in levels)
raise ValueError(
'Bad message level string: `%s`. Possible values are: %s'
% (level, levels_repr)
)
messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently) | [
"def",
"message_user",
"(",
"self",
",",
"request",
",",
"message",
",",
"level",
"=",
"messages",
".",
"INFO",
",",
"extra_tags",
"=",
"''",
",",
"fail_silently",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"int",
")",
":",
"# attempt to get the level if passed a string",
"try",
":",
"level",
"=",
"getattr",
"(",
"messages",
".",
"constants",
",",
"level",
".",
"upper",
"(",
")",
")",
"except",
"AttributeError",
":",
"levels",
"=",
"messages",
".",
"constants",
".",
"DEFAULT_TAGS",
".",
"values",
"(",
")",
"levels_repr",
"=",
"', '",
".",
"join",
"(",
"'`%s`'",
"%",
"level",
"for",
"level",
"in",
"levels",
")",
"raise",
"ValueError",
"(",
"'Bad message level string: `%s`. Possible values are: %s'",
"%",
"(",
"level",
",",
"levels_repr",
")",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"level",
",",
"message",
",",
"extra_tags",
"=",
"extra_tags",
",",
"fail_silently",
"=",
"fail_silently",
")"
] | [
1062,
4
] | [
1085,
105
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.save_form | (self, request, form, change) |
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
|
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
| def save_form(self, request, form, change):
"""
Given a ModelForm return an unsaved instance. ``change`` is True if
the object is being changed, and False if it's being added.
"""
return form.save(commit=False) | [
"def",
"save_form",
"(",
"self",
",",
"request",
",",
"form",
",",
"change",
")",
":",
"return",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")"
] | [
1087,
4
] | [
1092,
38
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.save_model | (self, request, obj, form, change) |
Given a model instance save it to the database.
|
Given a model instance save it to the database.
| def save_model(self, request, obj, form, change):
"""
Given a model instance save it to the database.
"""
obj.save() | [
"def",
"save_model",
"(",
"self",
",",
"request",
",",
"obj",
",",
"form",
",",
"change",
")",
":",
"obj",
".",
"save",
"(",
")"
] | [
1094,
4
] | [
1098,
18
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.delete_model | (self, request, obj) |
Given a model instance delete it from the database.
|
Given a model instance delete it from the database.
| def delete_model(self, request, obj):
"""
Given a model instance delete it from the database.
"""
obj.delete() | [
"def",
"delete_model",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"obj",
".",
"delete",
"(",
")"
] | [
1100,
4
] | [
1104,
20
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.delete_queryset | (self, request, queryset) | Given a queryset, delete it from the database. | Given a queryset, delete it from the database. | def delete_queryset(self, request, queryset):
"""Given a queryset, delete it from the database."""
queryset.delete() | [
"def",
"delete_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"queryset",
".",
"delete",
"(",
")"
] | [
1106,
4
] | [
1108,
25
] | python | en | ['en', 'en', 'en'] | True |
ModelAdmin.save_formset | (self, request, form, formset, change) |
Given an inline formset save it to the database.
|
Given an inline formset save it to the database.
| def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save() | [
"def",
"save_formset",
"(",
"self",
",",
"request",
",",
"form",
",",
"formset",
",",
"change",
")",
":",
"formset",
".",
"save",
"(",
")"
] | [
1110,
4
] | [
1114,
22
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.save_related | (self, request, form, formsets, change) |
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.
|
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.
| def save_related(self, request, form, formsets, change):
"""
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at this point save_form() and save_model() have
already been called.
"""
form.save_m2m()
for formset in formsets:
self.save_formset(request, form, formset, change=change) | [
"def",
"save_related",
"(",
"self",
",",
"request",
",",
"form",
",",
"formsets",
",",
"change",
")",
":",
"form",
".",
"save_m2m",
"(",
")",
"for",
"formset",
"in",
"formsets",
":",
"self",
".",
"save_formset",
"(",
"request",
",",
"form",
",",
"formset",
",",
"change",
"=",
"change",
")"
] | [
1116,
4
] | [
1126,
68
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.response_add | (self, request, obj, post_url_continue=None) |
Determine the HttpResponse for the add_view stage.
|
Determine the HttpResponse for the add_view stage.
| def response_add(self, request, obj, post_url_continue=None):
"""
Determine the HttpResponse for the add_view stage.
"""
opts = obj._meta
preserved_filters = self.get_preserved_filters(request)
obj_url = reverse(
'admin:%s_%s_change' % (opts.app_label, opts.model_name),
args=(quote(obj.pk),),
current_app=self.admin_site.name,
)
# Add a link to the object's change form if the user can edit the obj.
if self.has_change_permission(request, obj):
obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj)
else:
obj_repr = str(obj)
msg_dict = {
'name': opts.verbose_name,
'obj': obj_repr,
}
# Here, we distinguish between different save types by checking for
# the presence of keys in request.POST.
if IS_POPUP_VAR in request.POST:
to_field = request.POST.get(TO_FIELD_VAR)
if to_field:
attr = str(to_field)
else:
attr = obj._meta.pk.attname
value = obj.serializable_value(attr)
popup_response_data = json.dumps({
'value': str(value),
'obj': str(obj),
})
return TemplateResponse(request, self.popup_response_template or [
'admin/%s/%s/popup_response.html' % (opts.app_label, opts.model_name),
'admin/%s/popup_response.html' % opts.app_label,
'admin/popup_response.html',
], {
'popup_response_data': popup_response_data,
})
elif "_continue" in request.POST or (
# Redirecting after "Save as new".
"_saveasnew" in request.POST and self.save_as_continue and
self.has_change_permission(request, obj)
):
msg = _('The {name} “{obj}” was added successfully.')
if self.has_change_permission(request, obj):
msg += ' ' + _('You may edit it again below.')
self.message_user(request, format_html(msg, **msg_dict), messages.SUCCESS)
if post_url_continue is None:
post_url_continue = obj_url
post_url_continue = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts},
post_url_continue
)
return HttpResponseRedirect(post_url_continue)
elif "_addanother" in request.POST:
msg = format_html(
_('The {name} “{obj}” was added successfully. You may add another {name} below.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = request.path
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
else:
msg = format_html(
_('The {name} “{obj}” was added successfully.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
return self.response_post_save_add(request, obj) | [
"def",
"response_add",
"(",
"self",
",",
"request",
",",
"obj",
",",
"post_url_continue",
"=",
"None",
")",
":",
"opts",
"=",
"obj",
".",
"_meta",
"preserved_filters",
"=",
"self",
".",
"get_preserved_filters",
"(",
"request",
")",
"obj_url",
"=",
"reverse",
"(",
"'admin:%s_%s_change'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"args",
"=",
"(",
"quote",
"(",
"obj",
".",
"pk",
")",
",",
")",
",",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
",",
")",
"# Add a link to the object's change form if the user can edit the obj.",
"if",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
")",
":",
"obj_repr",
"=",
"format_html",
"(",
"'<a href=\"{}\">{}</a>'",
",",
"urlquote",
"(",
"obj_url",
")",
",",
"obj",
")",
"else",
":",
"obj_repr",
"=",
"str",
"(",
"obj",
")",
"msg_dict",
"=",
"{",
"'name'",
":",
"opts",
".",
"verbose_name",
",",
"'obj'",
":",
"obj_repr",
",",
"}",
"# Here, we distinguish between different save types by checking for",
"# the presence of keys in request.POST.",
"if",
"IS_POPUP_VAR",
"in",
"request",
".",
"POST",
":",
"to_field",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"TO_FIELD_VAR",
")",
"if",
"to_field",
":",
"attr",
"=",
"str",
"(",
"to_field",
")",
"else",
":",
"attr",
"=",
"obj",
".",
"_meta",
".",
"pk",
".",
"attname",
"value",
"=",
"obj",
".",
"serializable_value",
"(",
"attr",
")",
"popup_response_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'value'",
":",
"str",
"(",
"value",
")",
",",
"'obj'",
":",
"str",
"(",
"obj",
")",
",",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"self",
".",
"popup_response_template",
"or",
"[",
"'admin/%s/%s/popup_response.html'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"'admin/%s/popup_response.html'",
"%",
"opts",
".",
"app_label",
",",
"'admin/popup_response.html'",
",",
"]",
",",
"{",
"'popup_response_data'",
":",
"popup_response_data",
",",
"}",
")",
"elif",
"\"_continue\"",
"in",
"request",
".",
"POST",
"or",
"(",
"# Redirecting after \"Save as new\".",
"\"_saveasnew\"",
"in",
"request",
".",
"POST",
"and",
"self",
".",
"save_as_continue",
"and",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
")",
")",
":",
"msg",
"=",
"_",
"(",
"'The {name} “{obj}” was added successfully.')",
"",
"if",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
")",
":",
"msg",
"+=",
"' '",
"+",
"_",
"(",
"'You may edit it again below.'",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"format_html",
"(",
"msg",
",",
"*",
"*",
"msg_dict",
")",
",",
"messages",
".",
"SUCCESS",
")",
"if",
"post_url_continue",
"is",
"None",
":",
"post_url_continue",
"=",
"obj_url",
"post_url_continue",
"=",
"add_preserved_filters",
"(",
"{",
"'preserved_filters'",
":",
"preserved_filters",
",",
"'opts'",
":",
"opts",
"}",
",",
"post_url_continue",
")",
"return",
"HttpResponseRedirect",
"(",
"post_url_continue",
")",
"elif",
"\"_addanother\"",
"in",
"request",
".",
"POST",
":",
"msg",
"=",
"format_html",
"(",
"_",
"(",
"'The {name} “{obj}” was added successfully. You may add another {name} below.'),",
"",
"",
"*",
"*",
"msg_dict",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"redirect_url",
"=",
"request",
".",
"path",
"redirect_url",
"=",
"add_preserved_filters",
"(",
"{",
"'preserved_filters'",
":",
"preserved_filters",
",",
"'opts'",
":",
"opts",
"}",
",",
"redirect_url",
")",
"return",
"HttpResponseRedirect",
"(",
"redirect_url",
")",
"else",
":",
"msg",
"=",
"format_html",
"(",
"_",
"(",
"'The {name} “{obj}” was added successfully.'),",
"",
"",
"*",
"*",
"msg_dict",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"return",
"self",
".",
"response_post_save_add",
"(",
"request",
",",
"obj",
")"
] | [
1175,
4
] | [
1250,
60
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.response_change | (self, request, obj) |
Determine the HttpResponse for the change_view stage.
|
Determine the HttpResponse for the change_view stage.
| def response_change(self, request, obj):
"""
Determine the HttpResponse for the change_view stage.
"""
if IS_POPUP_VAR in request.POST:
opts = obj._meta
to_field = request.POST.get(TO_FIELD_VAR)
attr = str(to_field) if to_field else opts.pk.attname
value = request.resolver_match.kwargs['object_id']
new_value = obj.serializable_value(attr)
popup_response_data = json.dumps({
'action': 'change',
'value': str(value),
'obj': str(obj),
'new_value': str(new_value),
})
return TemplateResponse(request, self.popup_response_template or [
'admin/%s/%s/popup_response.html' % (opts.app_label, opts.model_name),
'admin/%s/popup_response.html' % opts.app_label,
'admin/popup_response.html',
], {
'popup_response_data': popup_response_data,
})
opts = self.model._meta
preserved_filters = self.get_preserved_filters(request)
msg_dict = {
'name': opts.verbose_name,
'obj': format_html('<a href="{}">{}</a>', urlquote(request.path), obj),
}
if "_continue" in request.POST:
msg = format_html(
_('The {name} “{obj}” was changed successfully. You may edit it again below.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = request.path
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
elif "_saveasnew" in request.POST:
msg = format_html(
_('The {name} “{obj}” was added successfully. You may edit it again below.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = reverse('admin:%s_%s_change' %
(opts.app_label, opts.model_name),
args=(obj.pk,),
current_app=self.admin_site.name)
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
elif "_addanother" in request.POST:
msg = format_html(
_('The {name} “{obj}” was changed successfully. You may add another {name} below.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
redirect_url = reverse('admin:%s_%s_add' %
(opts.app_label, opts.model_name),
current_app=self.admin_site.name)
redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url)
return HttpResponseRedirect(redirect_url)
else:
msg = format_html(
_('The {name} “{obj}” was changed successfully.'),
**msg_dict
)
self.message_user(request, msg, messages.SUCCESS)
return self.response_post_save_change(request, obj) | [
"def",
"response_change",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"if",
"IS_POPUP_VAR",
"in",
"request",
".",
"POST",
":",
"opts",
"=",
"obj",
".",
"_meta",
"to_field",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"TO_FIELD_VAR",
")",
"attr",
"=",
"str",
"(",
"to_field",
")",
"if",
"to_field",
"else",
"opts",
".",
"pk",
".",
"attname",
"value",
"=",
"request",
".",
"resolver_match",
".",
"kwargs",
"[",
"'object_id'",
"]",
"new_value",
"=",
"obj",
".",
"serializable_value",
"(",
"attr",
")",
"popup_response_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'action'",
":",
"'change'",
",",
"'value'",
":",
"str",
"(",
"value",
")",
",",
"'obj'",
":",
"str",
"(",
"obj",
")",
",",
"'new_value'",
":",
"str",
"(",
"new_value",
")",
",",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"self",
".",
"popup_response_template",
"or",
"[",
"'admin/%s/%s/popup_response.html'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"'admin/%s/popup_response.html'",
"%",
"opts",
".",
"app_label",
",",
"'admin/popup_response.html'",
",",
"]",
",",
"{",
"'popup_response_data'",
":",
"popup_response_data",
",",
"}",
")",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"preserved_filters",
"=",
"self",
".",
"get_preserved_filters",
"(",
"request",
")",
"msg_dict",
"=",
"{",
"'name'",
":",
"opts",
".",
"verbose_name",
",",
"'obj'",
":",
"format_html",
"(",
"'<a href=\"{}\">{}</a>'",
",",
"urlquote",
"(",
"request",
".",
"path",
")",
",",
"obj",
")",
",",
"}",
"if",
"\"_continue\"",
"in",
"request",
".",
"POST",
":",
"msg",
"=",
"format_html",
"(",
"_",
"(",
"'The {name} “{obj}” was changed successfully. You may edit it again below.'),",
"",
"",
"*",
"*",
"msg_dict",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"redirect_url",
"=",
"request",
".",
"path",
"redirect_url",
"=",
"add_preserved_filters",
"(",
"{",
"'preserved_filters'",
":",
"preserved_filters",
",",
"'opts'",
":",
"opts",
"}",
",",
"redirect_url",
")",
"return",
"HttpResponseRedirect",
"(",
"redirect_url",
")",
"elif",
"\"_saveasnew\"",
"in",
"request",
".",
"POST",
":",
"msg",
"=",
"format_html",
"(",
"_",
"(",
"'The {name} “{obj}” was added successfully. You may edit it again below.'),",
"",
"",
"*",
"*",
"msg_dict",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"redirect_url",
"=",
"reverse",
"(",
"'admin:%s_%s_change'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"args",
"=",
"(",
"obj",
".",
"pk",
",",
")",
",",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
")",
"redirect_url",
"=",
"add_preserved_filters",
"(",
"{",
"'preserved_filters'",
":",
"preserved_filters",
",",
"'opts'",
":",
"opts",
"}",
",",
"redirect_url",
")",
"return",
"HttpResponseRedirect",
"(",
"redirect_url",
")",
"elif",
"\"_addanother\"",
"in",
"request",
".",
"POST",
":",
"msg",
"=",
"format_html",
"(",
"_",
"(",
"'The {name} “{obj}” was changed successfully. You may add another {name} below.'),",
"",
"",
"*",
"*",
"msg_dict",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"redirect_url",
"=",
"reverse",
"(",
"'admin:%s_%s_add'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
")",
"redirect_url",
"=",
"add_preserved_filters",
"(",
"{",
"'preserved_filters'",
":",
"preserved_filters",
",",
"'opts'",
":",
"opts",
"}",
",",
"redirect_url",
")",
"return",
"HttpResponseRedirect",
"(",
"redirect_url",
")",
"else",
":",
"msg",
"=",
"format_html",
"(",
"_",
"(",
"'The {name} “{obj}” was changed successfully.'),",
"",
"",
"*",
"*",
"msg_dict",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"return",
"self",
".",
"response_post_save_change",
"(",
"request",
",",
"obj",
")"
] | [
1252,
4
] | [
1325,
63
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.response_post_save_add | (self, request, obj) |
Figure out where to redirect after the 'Save' button has been pressed
when adding a new object.
|
Figure out where to redirect after the 'Save' button has been pressed
when adding a new object.
| def response_post_save_add(self, request, obj):
"""
Figure out where to redirect after the 'Save' button has been pressed
when adding a new object.
"""
return self._response_post_save(request, obj) | [
"def",
"response_post_save_add",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"return",
"self",
".",
"_response_post_save",
"(",
"request",
",",
"obj",
")"
] | [
1340,
4
] | [
1345,
53
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.response_post_save_change | (self, request, obj) |
Figure out where to redirect after the 'Save' button has been pressed
when editing an existing object.
|
Figure out where to redirect after the 'Save' button has been pressed
when editing an existing object.
| def response_post_save_change(self, request, obj):
"""
Figure out where to redirect after the 'Save' button has been pressed
when editing an existing object.
"""
return self._response_post_save(request, obj) | [
"def",
"response_post_save_change",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"return",
"self",
".",
"_response_post_save",
"(",
"request",
",",
"obj",
")"
] | [
1347,
4
] | [
1352,
53
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.response_action | (self, request, queryset) |
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
|
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
| def response_action(self, request, queryset):
"""
Handle an admin action. This is called if a request is POSTed to the
changelist; it returns an HttpResponse if the action was handled, and
None otherwise.
"""
# There can be multiple action forms on the page (at the top
# and bottom of the change list, for example). Get the action
# whose button was pushed.
try:
action_index = int(request.POST.get('index', 0))
except ValueError:
action_index = 0
# Construct the action form.
data = request.POST.copy()
data.pop(helpers.ACTION_CHECKBOX_NAME, None)
data.pop("index", None)
# Use the action whose button was pushed
try:
data.update({'action': data.getlist('action')[action_index]})
except IndexError:
# If we didn't get an action from the chosen form that's invalid
# POST data, so by deleting action it'll fail the validation check
# below. So no need to do anything here
pass
action_form = self.action_form(data, auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
# If the form's valid we can handle the action.
if action_form.is_valid():
action = action_form.cleaned_data['action']
select_across = action_form.cleaned_data['select_across']
func = self.get_actions(request)[action][0]
# Get the list of selected PKs. If nothing's selected, we can't
# perform an action on it, so bail. Except we want to perform
# the action explicitly on all objects.
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
if not selected and not select_across:
# Reminder that something needs to be selected or nothing will happen
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg, messages.WARNING)
return None
if not select_across:
# Perform the action only on the selected objects
queryset = queryset.filter(pk__in=selected)
response = func(self, request, queryset)
# Actions may return an HttpResponse-like object, which will be
# used as the response from the POST. If not, we'll be a good
# little HTTP citizen and redirect back to the changelist page.
if isinstance(response, HttpResponseBase):
return response
else:
return HttpResponseRedirect(request.get_full_path())
else:
msg = _("No action selected.")
self.message_user(request, msg, messages.WARNING)
return None | [
"def",
"response_action",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"# There can be multiple action forms on the page (at the top",
"# and bottom of the change list, for example). Get the action",
"# whose button was pushed.",
"try",
":",
"action_index",
"=",
"int",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'index'",
",",
"0",
")",
")",
"except",
"ValueError",
":",
"action_index",
"=",
"0",
"# Construct the action form.",
"data",
"=",
"request",
".",
"POST",
".",
"copy",
"(",
")",
"data",
".",
"pop",
"(",
"helpers",
".",
"ACTION_CHECKBOX_NAME",
",",
"None",
")",
"data",
".",
"pop",
"(",
"\"index\"",
",",
"None",
")",
"# Use the action whose button was pushed",
"try",
":",
"data",
".",
"update",
"(",
"{",
"'action'",
":",
"data",
".",
"getlist",
"(",
"'action'",
")",
"[",
"action_index",
"]",
"}",
")",
"except",
"IndexError",
":",
"# If we didn't get an action from the chosen form that's invalid",
"# POST data, so by deleting action it'll fail the validation check",
"# below. So no need to do anything here",
"pass",
"action_form",
"=",
"self",
".",
"action_form",
"(",
"data",
",",
"auto_id",
"=",
"None",
")",
"action_form",
".",
"fields",
"[",
"'action'",
"]",
".",
"choices",
"=",
"self",
".",
"get_action_choices",
"(",
"request",
")",
"# If the form's valid we can handle the action.",
"if",
"action_form",
".",
"is_valid",
"(",
")",
":",
"action",
"=",
"action_form",
".",
"cleaned_data",
"[",
"'action'",
"]",
"select_across",
"=",
"action_form",
".",
"cleaned_data",
"[",
"'select_across'",
"]",
"func",
"=",
"self",
".",
"get_actions",
"(",
"request",
")",
"[",
"action",
"]",
"[",
"0",
"]",
"# Get the list of selected PKs. If nothing's selected, we can't",
"# perform an action on it, so bail. Except we want to perform",
"# the action explicitly on all objects.",
"selected",
"=",
"request",
".",
"POST",
".",
"getlist",
"(",
"helpers",
".",
"ACTION_CHECKBOX_NAME",
")",
"if",
"not",
"selected",
"and",
"not",
"select_across",
":",
"# Reminder that something needs to be selected or nothing will happen",
"msg",
"=",
"_",
"(",
"\"Items must be selected in order to perform \"",
"\"actions on them. No items have been changed.\"",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"WARNING",
")",
"return",
"None",
"if",
"not",
"select_across",
":",
"# Perform the action only on the selected objects",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"pk__in",
"=",
"selected",
")",
"response",
"=",
"func",
"(",
"self",
",",
"request",
",",
"queryset",
")",
"# Actions may return an HttpResponse-like object, which will be",
"# used as the response from the POST. If not, we'll be a good",
"# little HTTP citizen and redirect back to the changelist page.",
"if",
"isinstance",
"(",
"response",
",",
"HttpResponseBase",
")",
":",
"return",
"response",
"else",
":",
"return",
"HttpResponseRedirect",
"(",
"request",
".",
"get_full_path",
"(",
")",
")",
"else",
":",
"msg",
"=",
"_",
"(",
"\"No action selected.\"",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"WARNING",
")",
"return",
"None"
] | [
1354,
4
] | [
1419,
23
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.response_delete | (self, request, obj_display, obj_id) |
Determine the HttpResponse for the delete_view stage.
|
Determine the HttpResponse for the delete_view stage.
| def response_delete(self, request, obj_display, obj_id):
"""
Determine the HttpResponse for the delete_view stage.
"""
opts = self.model._meta
if IS_POPUP_VAR in request.POST:
popup_response_data = json.dumps({
'action': 'delete',
'value': str(obj_id),
})
return TemplateResponse(request, self.popup_response_template or [
'admin/%s/%s/popup_response.html' % (opts.app_label, opts.model_name),
'admin/%s/popup_response.html' % opts.app_label,
'admin/popup_response.html',
], {
'popup_response_data': popup_response_data,
})
self.message_user(
request,
_('The %(name)s “%(obj)s” was deleted successfully.') % {
'name': opts.verbose_name,
'obj': obj_display,
},
messages.SUCCESS,
)
if self.has_change_permission(request, None):
post_url = reverse(
'admin:%s_%s_changelist' % (opts.app_label, opts.model_name),
current_app=self.admin_site.name,
)
preserved_filters = self.get_preserved_filters(request)
post_url = add_preserved_filters(
{'preserved_filters': preserved_filters, 'opts': opts}, post_url
)
else:
post_url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(post_url) | [
"def",
"response_delete",
"(",
"self",
",",
"request",
",",
"obj_display",
",",
"obj_id",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"if",
"IS_POPUP_VAR",
"in",
"request",
".",
"POST",
":",
"popup_response_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'action'",
":",
"'delete'",
",",
"'value'",
":",
"str",
"(",
"obj_id",
")",
",",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"self",
".",
"popup_response_template",
"or",
"[",
"'admin/%s/%s/popup_response.html'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"'admin/%s/popup_response.html'",
"%",
"opts",
".",
"app_label",
",",
"'admin/popup_response.html'",
",",
"]",
",",
"{",
"'popup_response_data'",
":",
"popup_response_data",
",",
"}",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"_",
"(",
"'The %(name)s “%(obj)s” was deleted successfully.') % ",
"{",
"",
"",
"'name'",
":",
"opts",
".",
"verbose_name",
",",
"'obj'",
":",
"obj_display",
",",
"}",
",",
"messages",
".",
"SUCCESS",
",",
")",
"if",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"None",
")",
":",
"post_url",
"=",
"reverse",
"(",
"'admin:%s_%s_changelist'",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
",",
")",
"preserved_filters",
"=",
"self",
".",
"get_preserved_filters",
"(",
"request",
")",
"post_url",
"=",
"add_preserved_filters",
"(",
"{",
"'preserved_filters'",
":",
"preserved_filters",
",",
"'opts'",
":",
"opts",
"}",
",",
"post_url",
")",
"else",
":",
"post_url",
"=",
"reverse",
"(",
"'admin:index'",
",",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
")",
"return",
"HttpResponseRedirect",
"(",
"post_url",
")"
] | [
1421,
4
] | [
1460,
45
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_changeform_initial_data | (self, request) |
Get the initial form data from the request's GET params.
|
Get the initial form data from the request's GET params.
| def get_changeform_initial_data(self, request):
"""
Get the initial form data from the request's GET params.
"""
initial = dict(request.GET.items())
for k in initial:
try:
f = self.model._meta.get_field(k)
except FieldDoesNotExist:
continue
# We have to special-case M2Ms as a list of comma-separated PKs.
if isinstance(f, models.ManyToManyField):
initial[k] = initial[k].split(",")
return initial | [
"def",
"get_changeform_initial_data",
"(",
"self",
",",
"request",
")",
":",
"initial",
"=",
"dict",
"(",
"request",
".",
"GET",
".",
"items",
"(",
")",
")",
"for",
"k",
"in",
"initial",
":",
"try",
":",
"f",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"get_field",
"(",
"k",
")",
"except",
"FieldDoesNotExist",
":",
"continue",
"# We have to special-case M2Ms as a list of comma-separated PKs.",
"if",
"isinstance",
"(",
"f",
",",
"models",
".",
"ManyToManyField",
")",
":",
"initial",
"[",
"k",
"]",
"=",
"initial",
"[",
"k",
"]",
".",
"split",
"(",
"\",\"",
")",
"return",
"initial"
] | [
1508,
4
] | [
1521,
22
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin._get_obj_does_not_exist_redirect | (self, request, opts, object_id) |
Create a message informing the user that the object doesn't exist
and return a redirect to the admin index page.
|
Create a message informing the user that the object doesn't exist
and return a redirect to the admin index page.
| def _get_obj_does_not_exist_redirect(self, request, opts, object_id):
"""
Create a message informing the user that the object doesn't exist
and return a redirect to the admin index page.
"""
msg = _('%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?') % {
'name': opts.verbose_name,
'key': unquote(object_id),
}
self.message_user(request, msg, messages.WARNING)
url = reverse('admin:index', current_app=self.admin_site.name)
return HttpResponseRedirect(url) | [
"def",
"_get_obj_does_not_exist_redirect",
"(",
"self",
",",
"request",
",",
"opts",
",",
"object_id",
")",
":",
"msg",
"=",
"_",
"(",
"'%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?') % {",
"",
"",
"",
"'name'",
":",
"opts",
".",
"verbose_name",
",",
"'key'",
":",
"unquote",
"(",
"object_id",
")",
",",
"}",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"WARNING",
")",
"url",
"=",
"reverse",
"(",
"'admin:index'",
",",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
")",
"return",
"HttpResponseRedirect",
"(",
"url",
")"
] | [
1523,
4
] | [
1534,
40
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin._get_edited_object_pks | (self, request, prefix) | Return POST data values of list_editable primary keys. | Return POST data values of list_editable primary keys. | def _get_edited_object_pks(self, request, prefix):
"""Return POST data values of list_editable primary keys."""
pk_pattern = re.compile(
r'{}-\d+-{}$'.format(re.escape(prefix), self.model._meta.pk.name)
)
return [value for key, value in request.POST.items() if pk_pattern.match(key)] | [
"def",
"_get_edited_object_pks",
"(",
"self",
",",
"request",
",",
"prefix",
")",
":",
"pk_pattern",
"=",
"re",
".",
"compile",
"(",
"r'{}-\\d+-{}$'",
".",
"format",
"(",
"re",
".",
"escape",
"(",
"prefix",
")",
",",
"self",
".",
"model",
".",
"_meta",
".",
"pk",
".",
"name",
")",
")",
"return",
"[",
"value",
"for",
"key",
",",
"value",
"in",
"request",
".",
"POST",
".",
"items",
"(",
")",
"if",
"pk_pattern",
".",
"match",
"(",
"key",
")",
"]"
] | [
1661,
4
] | [
1666,
86
] | python | en | ['en', 'et', 'en'] | True |
ModelAdmin._get_list_editable_queryset | (self, request, prefix) |
Based on POST data, return a queryset of the objects that were edited
via list_editable.
|
Based on POST data, return a queryset of the objects that were edited
via list_editable.
| def _get_list_editable_queryset(self, request, prefix):
"""
Based on POST data, return a queryset of the objects that were edited
via list_editable.
"""
object_pks = self._get_edited_object_pks(request, prefix)
queryset = self.get_queryset(request)
validate = queryset.model._meta.pk.to_python
try:
for pk in object_pks:
validate(pk)
except ValidationError:
# Disable the optimization if the POST data was tampered with.
return queryset
return queryset.filter(pk__in=object_pks) | [
"def",
"_get_list_editable_queryset",
"(",
"self",
",",
"request",
",",
"prefix",
")",
":",
"object_pks",
"=",
"self",
".",
"_get_edited_object_pks",
"(",
"request",
",",
"prefix",
")",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
"request",
")",
"validate",
"=",
"queryset",
".",
"model",
".",
"_meta",
".",
"pk",
".",
"to_python",
"try",
":",
"for",
"pk",
"in",
"object_pks",
":",
"validate",
"(",
"pk",
")",
"except",
"ValidationError",
":",
"# Disable the optimization if the POST data was tampered with.",
"return",
"queryset",
"return",
"queryset",
".",
"filter",
"(",
"pk__in",
"=",
"object_pks",
")"
] | [
1668,
4
] | [
1682,
49
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.changelist_view | (self, request, extra_context=None) |
The 'change list' admin view for this model.
|
The 'change list' admin view for this model.
| def changelist_view(self, request, extra_context=None):
"""
The 'change list' admin view for this model.
"""
from django.contrib.admin.views.main import ERROR_FLAG
opts = self.model._meta
app_label = opts.app_label
if not self.has_view_or_change_permission(request):
raise PermissionDenied
try:
cl = self.get_changelist_instance(request)
except IncorrectLookupParameters:
# Wacky lookup parameters were given, so redirect to the main
# changelist page, without parameters, and pass an 'invalid=1'
# parameter via the query string. If wacky parameters were given
# and the 'invalid=1' parameter was already in the query string,
# something is screwed up with the database, so display an error
# page.
if ERROR_FLAG in request.GET:
return SimpleTemplateResponse('admin/invalid_setup.html', {
'title': _('Database error'),
})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
# If the request was POSTed, this might be a bulk action or a bulk
# edit. Try to look up an action or confirmation first, but if this
# isn't an action the POST will fall through to the bulk edit check,
# below.
action_failed = False
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
actions = self.get_actions(request)
# Actions with no confirmation
if (actions and request.method == 'POST' and
'index' in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_queryset(request))
if response:
return response
else:
action_failed = True
else:
msg = _("Items must be selected in order to perform "
"actions on them. No items have been changed.")
self.message_user(request, msg, messages.WARNING)
action_failed = True
# Actions with confirmation
if (actions and request.method == 'POST' and
helpers.ACTION_CHECKBOX_NAME in request.POST and
'index' not in request.POST and '_save' not in request.POST):
if selected:
response = self.response_action(request, queryset=cl.get_queryset(request))
if response:
return response
else:
action_failed = True
if action_failed:
# Redirect back to the changelist page to avoid resubmitting the
# form if the user refreshes the browser or uses the "No, take
# me back" button on the action confirmation page.
return HttpResponseRedirect(request.get_full_path())
# If we're allowing changelist editing, we need to construct a formset
# for the changelist given all the fields to be edited. Then we'll
# use the formset to validate/process POSTed data.
formset = cl.formset = None
# Handle POSTed bulk-edit data.
if request.method == 'POST' and cl.list_editable and '_save' in request.POST:
if not self.has_change_permission(request):
raise PermissionDenied
FormSet = self.get_changelist_formset(request)
modified_objects = self._get_list_editable_queryset(request, FormSet.get_default_prefix())
formset = cl.formset = FormSet(request.POST, request.FILES, queryset=modified_objects)
if formset.is_valid():
changecount = 0
for form in formset.forms:
if form.has_changed():
obj = self.save_form(request, form, change=True)
self.save_model(request, obj, form, change=True)
self.save_related(request, form, formsets=[], change=True)
change_msg = self.construct_change_message(request, form, None)
self.log_change(request, obj, change_msg)
changecount += 1
if changecount:
msg = ngettext(
"%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount
) % {
'count': changecount,
'name': model_ngettext(opts, changecount),
}
self.message_user(request, msg, messages.SUCCESS)
return HttpResponseRedirect(request.get_full_path())
# Handle GET -- construct a formset for display.
elif cl.list_editable and self.has_change_permission(request):
FormSet = self.get_changelist_formset(request)
formset = cl.formset = FormSet(queryset=cl.result_list)
# Build the list of media to be used by the formset.
if formset:
media = self.media + formset.media
else:
media = self.media
# Build the action form and populate it with available actions.
if actions:
action_form = self.action_form(auto_id=None)
action_form.fields['action'].choices = self.get_action_choices(request)
media += action_form.media
else:
action_form = None
selection_note_all = ngettext(
'%(total_count)s selected',
'All %(total_count)s selected',
cl.result_count
)
context = {
**self.admin_site.each_context(request),
'module_name': str(opts.verbose_name_plural),
'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
'selection_note_all': selection_note_all % {'total_count': cl.result_count},
'title': cl.title,
'subtitle': None,
'is_popup': cl.is_popup,
'to_field': cl.to_field,
'cl': cl,
'media': media,
'has_add_permission': self.has_add_permission(request),
'opts': cl.opts,
'action_form': action_form,
'actions_on_top': self.actions_on_top,
'actions_on_bottom': self.actions_on_bottom,
'actions_selection_counter': self.actions_selection_counter,
'preserved_filters': self.get_preserved_filters(request),
**(extra_context or {}),
}
request.current_app = self.admin_site.name
return TemplateResponse(request, self.change_list_template or [
'admin/%s/%s/change_list.html' % (app_label, opts.model_name),
'admin/%s/change_list.html' % app_label,
'admin/change_list.html'
], context) | [
"def",
"changelist_view",
"(",
"self",
",",
"request",
",",
"extra_context",
"=",
"None",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"views",
".",
"main",
"import",
"ERROR_FLAG",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"if",
"not",
"self",
".",
"has_view_or_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"try",
":",
"cl",
"=",
"self",
".",
"get_changelist_instance",
"(",
"request",
")",
"except",
"IncorrectLookupParameters",
":",
"# Wacky lookup parameters were given, so redirect to the main",
"# changelist page, without parameters, and pass an 'invalid=1'",
"# parameter via the query string. If wacky parameters were given",
"# and the 'invalid=1' parameter was already in the query string,",
"# something is screwed up with the database, so display an error",
"# page.",
"if",
"ERROR_FLAG",
"in",
"request",
".",
"GET",
":",
"return",
"SimpleTemplateResponse",
"(",
"'admin/invalid_setup.html'",
",",
"{",
"'title'",
":",
"_",
"(",
"'Database error'",
")",
",",
"}",
")",
"return",
"HttpResponseRedirect",
"(",
"request",
".",
"path",
"+",
"'?'",
"+",
"ERROR_FLAG",
"+",
"'=1'",
")",
"# If the request was POSTed, this might be a bulk action or a bulk",
"# edit. Try to look up an action or confirmation first, but if this",
"# isn't an action the POST will fall through to the bulk edit check,",
"# below.",
"action_failed",
"=",
"False",
"selected",
"=",
"request",
".",
"POST",
".",
"getlist",
"(",
"helpers",
".",
"ACTION_CHECKBOX_NAME",
")",
"actions",
"=",
"self",
".",
"get_actions",
"(",
"request",
")",
"# Actions with no confirmation",
"if",
"(",
"actions",
"and",
"request",
".",
"method",
"==",
"'POST'",
"and",
"'index'",
"in",
"request",
".",
"POST",
"and",
"'_save'",
"not",
"in",
"request",
".",
"POST",
")",
":",
"if",
"selected",
":",
"response",
"=",
"self",
".",
"response_action",
"(",
"request",
",",
"queryset",
"=",
"cl",
".",
"get_queryset",
"(",
"request",
")",
")",
"if",
"response",
":",
"return",
"response",
"else",
":",
"action_failed",
"=",
"True",
"else",
":",
"msg",
"=",
"_",
"(",
"\"Items must be selected in order to perform \"",
"\"actions on them. No items have been changed.\"",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"WARNING",
")",
"action_failed",
"=",
"True",
"# Actions with confirmation",
"if",
"(",
"actions",
"and",
"request",
".",
"method",
"==",
"'POST'",
"and",
"helpers",
".",
"ACTION_CHECKBOX_NAME",
"in",
"request",
".",
"POST",
"and",
"'index'",
"not",
"in",
"request",
".",
"POST",
"and",
"'_save'",
"not",
"in",
"request",
".",
"POST",
")",
":",
"if",
"selected",
":",
"response",
"=",
"self",
".",
"response_action",
"(",
"request",
",",
"queryset",
"=",
"cl",
".",
"get_queryset",
"(",
"request",
")",
")",
"if",
"response",
":",
"return",
"response",
"else",
":",
"action_failed",
"=",
"True",
"if",
"action_failed",
":",
"# Redirect back to the changelist page to avoid resubmitting the",
"# form if the user refreshes the browser or uses the \"No, take",
"# me back\" button on the action confirmation page.",
"return",
"HttpResponseRedirect",
"(",
"request",
".",
"get_full_path",
"(",
")",
")",
"# If we're allowing changelist editing, we need to construct a formset",
"# for the changelist given all the fields to be edited. Then we'll",
"# use the formset to validate/process POSTed data.",
"formset",
"=",
"cl",
".",
"formset",
"=",
"None",
"# Handle POSTed bulk-edit data.",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"cl",
".",
"list_editable",
"and",
"'_save'",
"in",
"request",
".",
"POST",
":",
"if",
"not",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"FormSet",
"=",
"self",
".",
"get_changelist_formset",
"(",
"request",
")",
"modified_objects",
"=",
"self",
".",
"_get_list_editable_queryset",
"(",
"request",
",",
"FormSet",
".",
"get_default_prefix",
"(",
")",
")",
"formset",
"=",
"cl",
".",
"formset",
"=",
"FormSet",
"(",
"request",
".",
"POST",
",",
"request",
".",
"FILES",
",",
"queryset",
"=",
"modified_objects",
")",
"if",
"formset",
".",
"is_valid",
"(",
")",
":",
"changecount",
"=",
"0",
"for",
"form",
"in",
"formset",
".",
"forms",
":",
"if",
"form",
".",
"has_changed",
"(",
")",
":",
"obj",
"=",
"self",
".",
"save_form",
"(",
"request",
",",
"form",
",",
"change",
"=",
"True",
")",
"self",
".",
"save_model",
"(",
"request",
",",
"obj",
",",
"form",
",",
"change",
"=",
"True",
")",
"self",
".",
"save_related",
"(",
"request",
",",
"form",
",",
"formsets",
"=",
"[",
"]",
",",
"change",
"=",
"True",
")",
"change_msg",
"=",
"self",
".",
"construct_change_message",
"(",
"request",
",",
"form",
",",
"None",
")",
"self",
".",
"log_change",
"(",
"request",
",",
"obj",
",",
"change_msg",
")",
"changecount",
"+=",
"1",
"if",
"changecount",
":",
"msg",
"=",
"ngettext",
"(",
"\"%(count)s %(name)s was changed successfully.\"",
",",
"\"%(count)s %(name)s were changed successfully.\"",
",",
"changecount",
")",
"%",
"{",
"'count'",
":",
"changecount",
",",
"'name'",
":",
"model_ngettext",
"(",
"opts",
",",
"changecount",
")",
",",
"}",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"messages",
".",
"SUCCESS",
")",
"return",
"HttpResponseRedirect",
"(",
"request",
".",
"get_full_path",
"(",
")",
")",
"# Handle GET -- construct a formset for display.",
"elif",
"cl",
".",
"list_editable",
"and",
"self",
".",
"has_change_permission",
"(",
"request",
")",
":",
"FormSet",
"=",
"self",
".",
"get_changelist_formset",
"(",
"request",
")",
"formset",
"=",
"cl",
".",
"formset",
"=",
"FormSet",
"(",
"queryset",
"=",
"cl",
".",
"result_list",
")",
"# Build the list of media to be used by the formset.",
"if",
"formset",
":",
"media",
"=",
"self",
".",
"media",
"+",
"formset",
".",
"media",
"else",
":",
"media",
"=",
"self",
".",
"media",
"# Build the action form and populate it with available actions.",
"if",
"actions",
":",
"action_form",
"=",
"self",
".",
"action_form",
"(",
"auto_id",
"=",
"None",
")",
"action_form",
".",
"fields",
"[",
"'action'",
"]",
".",
"choices",
"=",
"self",
".",
"get_action_choices",
"(",
"request",
")",
"media",
"+=",
"action_form",
".",
"media",
"else",
":",
"action_form",
"=",
"None",
"selection_note_all",
"=",
"ngettext",
"(",
"'%(total_count)s selected'",
",",
"'All %(total_count)s selected'",
",",
"cl",
".",
"result_count",
")",
"context",
"=",
"{",
"*",
"*",
"self",
".",
"admin_site",
".",
"each_context",
"(",
"request",
")",
",",
"'module_name'",
":",
"str",
"(",
"opts",
".",
"verbose_name_plural",
")",
",",
"'selection_note'",
":",
"_",
"(",
"'0 of %(cnt)s selected'",
")",
"%",
"{",
"'cnt'",
":",
"len",
"(",
"cl",
".",
"result_list",
")",
"}",
",",
"'selection_note_all'",
":",
"selection_note_all",
"%",
"{",
"'total_count'",
":",
"cl",
".",
"result_count",
"}",
",",
"'title'",
":",
"cl",
".",
"title",
",",
"'subtitle'",
":",
"None",
",",
"'is_popup'",
":",
"cl",
".",
"is_popup",
",",
"'to_field'",
":",
"cl",
".",
"to_field",
",",
"'cl'",
":",
"cl",
",",
"'media'",
":",
"media",
",",
"'has_add_permission'",
":",
"self",
".",
"has_add_permission",
"(",
"request",
")",
",",
"'opts'",
":",
"cl",
".",
"opts",
",",
"'action_form'",
":",
"action_form",
",",
"'actions_on_top'",
":",
"self",
".",
"actions_on_top",
",",
"'actions_on_bottom'",
":",
"self",
".",
"actions_on_bottom",
",",
"'actions_selection_counter'",
":",
"self",
".",
"actions_selection_counter",
",",
"'preserved_filters'",
":",
"self",
".",
"get_preserved_filters",
"(",
"request",
")",
",",
"*",
"*",
"(",
"extra_context",
"or",
"{",
"}",
")",
",",
"}",
"request",
".",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
"return",
"TemplateResponse",
"(",
"request",
",",
"self",
".",
"change_list_template",
"or",
"[",
"'admin/%s/%s/change_list.html'",
"%",
"(",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"'admin/%s/change_list.html'",
"%",
"app_label",
",",
"'admin/change_list.html'",
"]",
",",
"context",
")"
] | [
1685,
4
] | [
1838,
19
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin.get_deleted_objects | (self, objs, request) |
Hook for customizing the delete process for the delete view and the
"delete selected" action.
|
Hook for customizing the delete process for the delete view and the
"delete selected" action.
| def get_deleted_objects(self, objs, request):
"""
Hook for customizing the delete process for the delete view and the
"delete selected" action.
"""
return get_deleted_objects(objs, request, self.admin_site) | [
"def",
"get_deleted_objects",
"(",
"self",
",",
"objs",
",",
"request",
")",
":",
"return",
"get_deleted_objects",
"(",
"objs",
",",
"request",
",",
"self",
".",
"admin_site",
")"
] | [
1840,
4
] | [
1845,
66
] | python | en | ['en', 'error', 'th'] | False |
ModelAdmin._delete_view | (self, request, object_id, extra_context) | The 'delete' admin view for this model. | The 'delete' admin view for this model. | def _delete_view(self, request, object_id, extra_context):
"The 'delete' admin view for this model."
opts = self.model._meta
app_label = opts.app_label
to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
if to_field and not self.to_field_allowed(request, to_field):
raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)
obj = self.get_object(request, unquote(object_id), to_field)
if not self.has_delete_permission(request, obj):
raise PermissionDenied
if obj is None:
return self._get_obj_does_not_exist_redirect(request, opts, object_id)
# Populate deleted_objects, a data structure of all related objects that
# will also be deleted.
deleted_objects, model_count, perms_needed, protected = self.get_deleted_objects([obj], request)
if request.POST and not protected: # The user has confirmed the deletion.
if perms_needed:
raise PermissionDenied
obj_display = str(obj)
attr = str(to_field) if to_field else opts.pk.attname
obj_id = obj.serializable_value(attr)
self.log_deletion(request, obj, obj_display)
self.delete_model(request, obj)
return self.response_delete(request, obj_display, obj_id)
object_name = str(opts.verbose_name)
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
title = _("Are you sure?")
context = {
**self.admin_site.each_context(request),
'title': title,
'subtitle': None,
'object_name': object_name,
'object': obj,
'deleted_objects': deleted_objects,
'model_count': dict(model_count).items(),
'perms_lacking': perms_needed,
'protected': protected,
'opts': opts,
'app_label': app_label,
'preserved_filters': self.get_preserved_filters(request),
'is_popup': IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET,
'to_field': to_field,
**(extra_context or {}),
}
return self.render_delete_form(request, context) | [
"def",
"_delete_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
")",
":",
"opts",
"=",
"self",
".",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"to_field",
"=",
"request",
".",
"POST",
".",
"get",
"(",
"TO_FIELD_VAR",
",",
"request",
".",
"GET",
".",
"get",
"(",
"TO_FIELD_VAR",
")",
")",
"if",
"to_field",
"and",
"not",
"self",
".",
"to_field_allowed",
"(",
"request",
",",
"to_field",
")",
":",
"raise",
"DisallowedModelAdminToField",
"(",
"\"The field %s cannot be referenced.\"",
"%",
"to_field",
")",
"obj",
"=",
"self",
".",
"get_object",
"(",
"request",
",",
"unquote",
"(",
"object_id",
")",
",",
"to_field",
")",
"if",
"not",
"self",
".",
"has_delete_permission",
"(",
"request",
",",
"obj",
")",
":",
"raise",
"PermissionDenied",
"if",
"obj",
"is",
"None",
":",
"return",
"self",
".",
"_get_obj_does_not_exist_redirect",
"(",
"request",
",",
"opts",
",",
"object_id",
")",
"# Populate deleted_objects, a data structure of all related objects that",
"# will also be deleted.",
"deleted_objects",
",",
"model_count",
",",
"perms_needed",
",",
"protected",
"=",
"self",
".",
"get_deleted_objects",
"(",
"[",
"obj",
"]",
",",
"request",
")",
"if",
"request",
".",
"POST",
"and",
"not",
"protected",
":",
"# The user has confirmed the deletion.",
"if",
"perms_needed",
":",
"raise",
"PermissionDenied",
"obj_display",
"=",
"str",
"(",
"obj",
")",
"attr",
"=",
"str",
"(",
"to_field",
")",
"if",
"to_field",
"else",
"opts",
".",
"pk",
".",
"attname",
"obj_id",
"=",
"obj",
".",
"serializable_value",
"(",
"attr",
")",
"self",
".",
"log_deletion",
"(",
"request",
",",
"obj",
",",
"obj_display",
")",
"self",
".",
"delete_model",
"(",
"request",
",",
"obj",
")",
"return",
"self",
".",
"response_delete",
"(",
"request",
",",
"obj_display",
",",
"obj_id",
")",
"object_name",
"=",
"str",
"(",
"opts",
".",
"verbose_name",
")",
"if",
"perms_needed",
"or",
"protected",
":",
"title",
"=",
"_",
"(",
"\"Cannot delete %(name)s\"",
")",
"%",
"{",
"\"name\"",
":",
"object_name",
"}",
"else",
":",
"title",
"=",
"_",
"(",
"\"Are you sure?\"",
")",
"context",
"=",
"{",
"*",
"*",
"self",
".",
"admin_site",
".",
"each_context",
"(",
"request",
")",
",",
"'title'",
":",
"title",
",",
"'subtitle'",
":",
"None",
",",
"'object_name'",
":",
"object_name",
",",
"'object'",
":",
"obj",
",",
"'deleted_objects'",
":",
"deleted_objects",
",",
"'model_count'",
":",
"dict",
"(",
"model_count",
")",
".",
"items",
"(",
")",
",",
"'perms_lacking'",
":",
"perms_needed",
",",
"'protected'",
":",
"protected",
",",
"'opts'",
":",
"opts",
",",
"'app_label'",
":",
"app_label",
",",
"'preserved_filters'",
":",
"self",
".",
"get_preserved_filters",
"(",
"request",
")",
",",
"'is_popup'",
":",
"IS_POPUP_VAR",
"in",
"request",
".",
"POST",
"or",
"IS_POPUP_VAR",
"in",
"request",
".",
"GET",
",",
"'to_field'",
":",
"to_field",
",",
"*",
"*",
"(",
"extra_context",
"or",
"{",
"}",
")",
",",
"}",
"return",
"self",
".",
"render_delete_form",
"(",
"request",
",",
"context",
")"
] | [
1852,
4
] | [
1909,
56
] | python | en | ['en', 'en', 'en'] | True |
ModelAdmin.history_view | (self, request, object_id, extra_context=None) | The 'history' admin view for this model. | The 'history' admin view for this model. | def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
# First check if the user can see this history.
model = self.model
obj = self.get_object(request, unquote(object_id))
if obj is None:
return self._get_obj_does_not_exist_redirect(request, model._meta, object_id)
if not self.has_view_or_change_permission(request, obj):
raise PermissionDenied
# Then get the history for this object.
opts = model._meta
app_label = opts.app_label
action_list = LogEntry.objects.filter(
object_id=unquote(object_id),
content_type=get_content_type_for_model(model)
).select_related().order_by('action_time')
context = {
**self.admin_site.each_context(request),
'title': _('Change history: %s') % obj,
'subtitle': None,
'action_list': action_list,
'module_name': str(capfirst(opts.verbose_name_plural)),
'object': obj,
'opts': opts,
'preserved_filters': self.get_preserved_filters(request),
**(extra_context or {}),
}
request.current_app = self.admin_site.name
return TemplateResponse(request, self.object_history_template or [
"admin/%s/%s/object_history.html" % (app_label, opts.model_name),
"admin/%s/object_history.html" % app_label,
"admin/object_history.html"
], context) | [
"def",
"history_view",
"(",
"self",
",",
"request",
",",
"object_id",
",",
"extra_context",
"=",
"None",
")",
":",
"from",
"django",
".",
"contrib",
".",
"admin",
".",
"models",
"import",
"LogEntry",
"# First check if the user can see this history.",
"model",
"=",
"self",
".",
"model",
"obj",
"=",
"self",
".",
"get_object",
"(",
"request",
",",
"unquote",
"(",
"object_id",
")",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"self",
".",
"_get_obj_does_not_exist_redirect",
"(",
"request",
",",
"model",
".",
"_meta",
",",
"object_id",
")",
"if",
"not",
"self",
".",
"has_view_or_change_permission",
"(",
"request",
",",
"obj",
")",
":",
"raise",
"PermissionDenied",
"# Then get the history for this object.",
"opts",
"=",
"model",
".",
"_meta",
"app_label",
"=",
"opts",
".",
"app_label",
"action_list",
"=",
"LogEntry",
".",
"objects",
".",
"filter",
"(",
"object_id",
"=",
"unquote",
"(",
"object_id",
")",
",",
"content_type",
"=",
"get_content_type_for_model",
"(",
"model",
")",
")",
".",
"select_related",
"(",
")",
".",
"order_by",
"(",
"'action_time'",
")",
"context",
"=",
"{",
"*",
"*",
"self",
".",
"admin_site",
".",
"each_context",
"(",
"request",
")",
",",
"'title'",
":",
"_",
"(",
"'Change history: %s'",
")",
"%",
"obj",
",",
"'subtitle'",
":",
"None",
",",
"'action_list'",
":",
"action_list",
",",
"'module_name'",
":",
"str",
"(",
"capfirst",
"(",
"opts",
".",
"verbose_name_plural",
")",
")",
",",
"'object'",
":",
"obj",
",",
"'opts'",
":",
"opts",
",",
"'preserved_filters'",
":",
"self",
".",
"get_preserved_filters",
"(",
"request",
")",
",",
"*",
"*",
"(",
"extra_context",
"or",
"{",
"}",
")",
",",
"}",
"request",
".",
"current_app",
"=",
"self",
".",
"admin_site",
".",
"name",
"return",
"TemplateResponse",
"(",
"request",
",",
"self",
".",
"object_history_template",
"or",
"[",
"\"admin/%s/%s/object_history.html\"",
"%",
"(",
"app_label",
",",
"opts",
".",
"model_name",
")",
",",
"\"admin/%s/object_history.html\"",
"%",
"app_label",
",",
"\"admin/object_history.html\"",
"]",
",",
"context",
")"
] | [
1911,
4
] | [
1950,
19
] | python | en | ['en', 'en', 'en'] | True |
ModelAdmin._create_formsets | (self, request, obj, change) | Helper function to generate formsets for add/change_view. | Helper function to generate formsets for add/change_view. | def _create_formsets(self, request, obj, change):
"Helper function to generate formsets for add/change_view."
formsets = []
inline_instances = []
prefixes = {}
get_formsets_args = [request]
if change:
get_formsets_args.append(obj)
for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args):
prefix = FormSet.get_default_prefix()
prefixes[prefix] = prefixes.get(prefix, 0) + 1
if prefixes[prefix] != 1 or not prefix:
prefix = "%s-%s" % (prefix, prefixes[prefix])
formset_params = {
'instance': obj,
'prefix': prefix,
'queryset': inline.get_queryset(request),
}
if request.method == 'POST':
formset_params.update({
'data': request.POST.copy(),
'files': request.FILES,
'save_as_new': '_saveasnew' in request.POST
})
formset = FormSet(**formset_params)
def user_deleted_form(request, obj, formset, index):
"""Return whether or not the user deleted the form."""
return (
inline.has_delete_permission(request, obj) and
'{}-{}-DELETE'.format(formset.prefix, index) in request.POST
)
# Bypass validation of each view-only inline form (since the form's
# data won't be in request.POST), unless the form was deleted.
if not inline.has_change_permission(request, obj if change else None):
for index, form in enumerate(formset.initial_forms):
if user_deleted_form(request, obj, formset, index):
continue
form._errors = {}
form.cleaned_data = form.initial
formsets.append(formset)
inline_instances.append(inline)
return formsets, inline_instances | [
"def",
"_create_formsets",
"(",
"self",
",",
"request",
",",
"obj",
",",
"change",
")",
":",
"formsets",
"=",
"[",
"]",
"inline_instances",
"=",
"[",
"]",
"prefixes",
"=",
"{",
"}",
"get_formsets_args",
"=",
"[",
"request",
"]",
"if",
"change",
":",
"get_formsets_args",
".",
"append",
"(",
"obj",
")",
"for",
"FormSet",
",",
"inline",
"in",
"self",
".",
"get_formsets_with_inlines",
"(",
"*",
"get_formsets_args",
")",
":",
"prefix",
"=",
"FormSet",
".",
"get_default_prefix",
"(",
")",
"prefixes",
"[",
"prefix",
"]",
"=",
"prefixes",
".",
"get",
"(",
"prefix",
",",
"0",
")",
"+",
"1",
"if",
"prefixes",
"[",
"prefix",
"]",
"!=",
"1",
"or",
"not",
"prefix",
":",
"prefix",
"=",
"\"%s-%s\"",
"%",
"(",
"prefix",
",",
"prefixes",
"[",
"prefix",
"]",
")",
"formset_params",
"=",
"{",
"'instance'",
":",
"obj",
",",
"'prefix'",
":",
"prefix",
",",
"'queryset'",
":",
"inline",
".",
"get_queryset",
"(",
"request",
")",
",",
"}",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"formset_params",
".",
"update",
"(",
"{",
"'data'",
":",
"request",
".",
"POST",
".",
"copy",
"(",
")",
",",
"'files'",
":",
"request",
".",
"FILES",
",",
"'save_as_new'",
":",
"'_saveasnew'",
"in",
"request",
".",
"POST",
"}",
")",
"formset",
"=",
"FormSet",
"(",
"*",
"*",
"formset_params",
")",
"def",
"user_deleted_form",
"(",
"request",
",",
"obj",
",",
"formset",
",",
"index",
")",
":",
"\"\"\"Return whether or not the user deleted the form.\"\"\"",
"return",
"(",
"inline",
".",
"has_delete_permission",
"(",
"request",
",",
"obj",
")",
"and",
"'{}-{}-DELETE'",
".",
"format",
"(",
"formset",
".",
"prefix",
",",
"index",
")",
"in",
"request",
".",
"POST",
")",
"# Bypass validation of each view-only inline form (since the form's",
"# data won't be in request.POST), unless the form was deleted.",
"if",
"not",
"inline",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
"if",
"change",
"else",
"None",
")",
":",
"for",
"index",
",",
"form",
"in",
"enumerate",
"(",
"formset",
".",
"initial_forms",
")",
":",
"if",
"user_deleted_form",
"(",
"request",
",",
"obj",
",",
"formset",
",",
"index",
")",
":",
"continue",
"form",
".",
"_errors",
"=",
"{",
"}",
"form",
".",
"cleaned_data",
"=",
"form",
".",
"initial",
"formsets",
".",
"append",
"(",
"formset",
")",
"inline_instances",
".",
"append",
"(",
"inline",
")",
"return",
"formsets",
",",
"inline_instances"
] | [
1952,
4
] | [
1995,
41
] | python | en | ['en', 'en', 'en'] | True |
InlineModelAdmin.get_extra | (self, request, obj=None, **kwargs) | Hook for customizing the number of extra inline forms. | Hook for customizing the number of extra inline forms. | def get_extra(self, request, obj=None, **kwargs):
"""Hook for customizing the number of extra inline forms."""
return self.extra | [
"def",
"get_extra",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"extra"
] | [
2041,
4
] | [
2043,
25
] | python | en | ['en', 'en', 'en'] | True |
InlineModelAdmin.get_min_num | (self, request, obj=None, **kwargs) | Hook for customizing the min number of inline forms. | Hook for customizing the min number of inline forms. | def get_min_num(self, request, obj=None, **kwargs):
"""Hook for customizing the min number of inline forms."""
return self.min_num | [
"def",
"get_min_num",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"min_num"
] | [
2045,
4
] | [
2047,
27
] | python | en | ['en', 'en', 'en'] | True |
InlineModelAdmin.get_max_num | (self, request, obj=None, **kwargs) | Hook for customizing the max number of extra inline forms. | Hook for customizing the max number of extra inline forms. | def get_max_num(self, request, obj=None, **kwargs):
"""Hook for customizing the max number of extra inline forms."""
return self.max_num | [
"def",
"get_max_num",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"max_num"
] | [
2049,
4
] | [
2051,
27
] | python | en | ['en', 'en', 'en'] | True |
InlineModelAdmin.get_formset | (self, request, obj=None, **kwargs) | Return a BaseInlineFormSet class for use in admin add/change views. | Return a BaseInlineFormSet class for use in admin add/change views. | def get_formset(self, request, obj=None, **kwargs):
"""Return a BaseInlineFormSet class for use in admin add/change views."""
if 'fields' in kwargs:
fields = kwargs.pop('fields')
else:
fields = flatten_fieldsets(self.get_fieldsets(request, obj))
excluded = self.get_exclude(request, obj)
exclude = [] if excluded is None else list(excluded)
exclude.extend(self.get_readonly_fields(request, obj))
if excluded is None and hasattr(self.form, '_meta') and self.form._meta.exclude:
# Take the custom ModelForm's Meta.exclude into account only if the
# InlineModelAdmin doesn't define its own.
exclude.extend(self.form._meta.exclude)
# If exclude is an empty list we use None, since that's the actual
# default.
exclude = exclude or None
can_delete = self.can_delete and self.has_delete_permission(request, obj)
defaults = {
'form': self.form,
'formset': self.formset,
'fk_name': self.fk_name,
'fields': fields,
'exclude': exclude,
'formfield_callback': partial(self.formfield_for_dbfield, request=request),
'extra': self.get_extra(request, obj, **kwargs),
'min_num': self.get_min_num(request, obj, **kwargs),
'max_num': self.get_max_num(request, obj, **kwargs),
'can_delete': can_delete,
**kwargs,
}
base_model_form = defaults['form']
can_change = self.has_change_permission(request, obj) if request else True
can_add = self.has_add_permission(request, obj) if request else True
class DeleteProtectedModelForm(base_model_form):
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):
using = router.db_for_write(self._meta.model)
collector = NestedObjects(using=using)
if self.instance._state.adding:
return
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)
def is_valid(self):
result = super().is_valid()
self.hand_clean_DELETE()
return result
def has_changed(self):
# Protect against unauthorized edits.
if not can_change and not self.instance._state.adding:
return False
if not can_add and self.instance._state.adding:
return False
return super().has_changed()
defaults['form'] = DeleteProtectedModelForm
if defaults['fields'] is None and not modelform_defines_fields(defaults['form']):
defaults['fields'] = forms.ALL_FIELDS
return inlineformset_factory(self.parent_model, self.model, **defaults) | [
"def",
"get_formset",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'fields'",
"in",
"kwargs",
":",
"fields",
"=",
"kwargs",
".",
"pop",
"(",
"'fields'",
")",
"else",
":",
"fields",
"=",
"flatten_fieldsets",
"(",
"self",
".",
"get_fieldsets",
"(",
"request",
",",
"obj",
")",
")",
"excluded",
"=",
"self",
".",
"get_exclude",
"(",
"request",
",",
"obj",
")",
"exclude",
"=",
"[",
"]",
"if",
"excluded",
"is",
"None",
"else",
"list",
"(",
"excluded",
")",
"exclude",
".",
"extend",
"(",
"self",
".",
"get_readonly_fields",
"(",
"request",
",",
"obj",
")",
")",
"if",
"excluded",
"is",
"None",
"and",
"hasattr",
"(",
"self",
".",
"form",
",",
"'_meta'",
")",
"and",
"self",
".",
"form",
".",
"_meta",
".",
"exclude",
":",
"# Take the custom ModelForm's Meta.exclude into account only if the",
"# InlineModelAdmin doesn't define its own.",
"exclude",
".",
"extend",
"(",
"self",
".",
"form",
".",
"_meta",
".",
"exclude",
")",
"# If exclude is an empty list we use None, since that's the actual",
"# default.",
"exclude",
"=",
"exclude",
"or",
"None",
"can_delete",
"=",
"self",
".",
"can_delete",
"and",
"self",
".",
"has_delete_permission",
"(",
"request",
",",
"obj",
")",
"defaults",
"=",
"{",
"'form'",
":",
"self",
".",
"form",
",",
"'formset'",
":",
"self",
".",
"formset",
",",
"'fk_name'",
":",
"self",
".",
"fk_name",
",",
"'fields'",
":",
"fields",
",",
"'exclude'",
":",
"exclude",
",",
"'formfield_callback'",
":",
"partial",
"(",
"self",
".",
"formfield_for_dbfield",
",",
"request",
"=",
"request",
")",
",",
"'extra'",
":",
"self",
".",
"get_extra",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
",",
"'min_num'",
":",
"self",
".",
"get_min_num",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
",",
"'max_num'",
":",
"self",
".",
"get_max_num",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
",",
"'can_delete'",
":",
"can_delete",
",",
"*",
"*",
"kwargs",
",",
"}",
"base_model_form",
"=",
"defaults",
"[",
"'form'",
"]",
"can_change",
"=",
"self",
".",
"has_change_permission",
"(",
"request",
",",
"obj",
")",
"if",
"request",
"else",
"True",
"can_add",
"=",
"self",
".",
"has_add_permission",
"(",
"request",
",",
"obj",
")",
"if",
"request",
"else",
"True",
"class",
"DeleteProtectedModelForm",
"(",
"base_model_form",
")",
":",
"def",
"hand_clean_DELETE",
"(",
"self",
")",
":",
"\"\"\"\n We don't validate the 'DELETE' field itself because on\n templates it's not rendered using the field information, but\n just using a generic \"deletion_field\" of the InlineModelAdmin.\n \"\"\"",
"if",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"DELETION_FIELD_NAME",
",",
"False",
")",
":",
"using",
"=",
"router",
".",
"db_for_write",
"(",
"self",
".",
"_meta",
".",
"model",
")",
"collector",
"=",
"NestedObjects",
"(",
"using",
"=",
"using",
")",
"if",
"self",
".",
"instance",
".",
"_state",
".",
"adding",
":",
"return",
"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",
")",
"def",
"is_valid",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
")",
".",
"is_valid",
"(",
")",
"self",
".",
"hand_clean_DELETE",
"(",
")",
"return",
"result",
"def",
"has_changed",
"(",
"self",
")",
":",
"# Protect against unauthorized edits.",
"if",
"not",
"can_change",
"and",
"not",
"self",
".",
"instance",
".",
"_state",
".",
"adding",
":",
"return",
"False",
"if",
"not",
"can_add",
"and",
"self",
".",
"instance",
".",
"_state",
".",
"adding",
":",
"return",
"False",
"return",
"super",
"(",
")",
".",
"has_changed",
"(",
")",
"defaults",
"[",
"'form'",
"]",
"=",
"DeleteProtectedModelForm",
"if",
"defaults",
"[",
"'fields'",
"]",
"is",
"None",
"and",
"not",
"modelform_defines_fields",
"(",
"defaults",
"[",
"'form'",
"]",
")",
":",
"defaults",
"[",
"'fields'",
"]",
"=",
"forms",
".",
"ALL_FIELDS",
"return",
"inlineformset_factory",
"(",
"self",
".",
"parent_model",
",",
"self",
".",
"model",
",",
"*",
"*",
"defaults",
")"
] | [
2053,
4
] | [
2140,
79
] | python | en | ['en', 'en', 'en'] | True |
InlineModelAdmin._has_any_perms_for_target_model | (self, request, perms) |
This method is called only when the ModelAdmin's model is for an
ManyToManyField's implicit through model (if self.opts.auto_created).
Return True if the user has any of the given permissions ('add',
'change', etc.) for the model that points to the through model.
|
This method is called only when the ModelAdmin's model is for an
ManyToManyField's implicit through model (if self.opts.auto_created).
Return True if the user has any of the given permissions ('add',
'change', etc.) for the model that points to the through model.
| def _has_any_perms_for_target_model(self, request, perms):
"""
This method is called only when the ModelAdmin's model is for an
ManyToManyField's implicit through model (if self.opts.auto_created).
Return True if the user has any of the given permissions ('add',
'change', etc.) for the model that points to the through model.
"""
opts = self.opts
# Find the target model of an auto-created many-to-many relationship.
for field in opts.fields:
if field.remote_field and field.remote_field.model != self.parent_model:
opts = field.remote_field.model._meta
break
return any(
request.user.has_perm('%s.%s' % (opts.app_label, get_permission_codename(perm, opts)))
for perm in perms
) | [
"def",
"_has_any_perms_for_target_model",
"(",
"self",
",",
"request",
",",
"perms",
")",
":",
"opts",
"=",
"self",
".",
"opts",
"# Find the target model of an auto-created many-to-many relationship.",
"for",
"field",
"in",
"opts",
".",
"fields",
":",
"if",
"field",
".",
"remote_field",
"and",
"field",
".",
"remote_field",
".",
"model",
"!=",
"self",
".",
"parent_model",
":",
"opts",
"=",
"field",
".",
"remote_field",
".",
"model",
".",
"_meta",
"break",
"return",
"any",
"(",
"request",
".",
"user",
".",
"has_perm",
"(",
"'%s.%s'",
"%",
"(",
"opts",
".",
"app_label",
",",
"get_permission_codename",
"(",
"perm",
",",
"opts",
")",
")",
")",
"for",
"perm",
"in",
"perms",
")"
] | [
2151,
4
] | [
2167,
9
] | python | en | ['en', 'error', 'th'] | False |
DictionaryStorage.__init__ | (self, dictionary, key, lock=None) | Construct a DictionaryStorage instance. | Construct a DictionaryStorage instance. | def __init__(self, dictionary, key, lock=None):
"""Construct a DictionaryStorage instance."""
super(DictionaryStorage, self).__init__(lock=lock)
self._dictionary = dictionary
self._key = key | [
"def",
"__init__",
"(",
"self",
",",
"dictionary",
",",
"key",
",",
"lock",
"=",
"None",
")",
":",
"super",
"(",
"DictionaryStorage",
",",
"self",
")",
".",
"__init__",
"(",
"lock",
"=",
"lock",
")",
"self",
".",
"_dictionary",
"=",
"dictionary",
"self",
".",
"_key",
"=",
"key"
] | [
31,
4
] | [
35,
23
] | python | en | ['en', 'en', 'en'] | True |
DictionaryStorage.locked_get | (self) | Retrieve the credentials from the dictionary, if they exist.
Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.
| Retrieve the credentials from the dictionary, if they exist. | def locked_get(self):
"""Retrieve the credentials from the dictionary, if they exist.
Returns: A :class:`oauth2client.client.OAuth2Credentials` instance.
"""
serialized = self._dictionary.get(self._key)
if serialized is None:
return None
credentials = client.OAuth2Credentials.from_json(serialized)
credentials.set_store(self)
return credentials | [
"def",
"locked_get",
"(",
"self",
")",
":",
"serialized",
"=",
"self",
".",
"_dictionary",
".",
"get",
"(",
"self",
".",
"_key",
")",
"if",
"serialized",
"is",
"None",
":",
"return",
"None",
"credentials",
"=",
"client",
".",
"OAuth2Credentials",
".",
"from_json",
"(",
"serialized",
")",
"credentials",
".",
"set_store",
"(",
"self",
")",
"return",
"credentials"
] | [
37,
4
] | [
50,
26
] | python | en | ['en', 'en', 'en'] | True |
DictionaryStorage.locked_put | (self, credentials) | Save the credentials to the dictionary.
Args:
credentials: A :class:`oauth2client.client.OAuth2Credentials`
instance.
| Save the credentials to the dictionary. | def locked_put(self, credentials):
"""Save the credentials to the dictionary.
Args:
credentials: A :class:`oauth2client.client.OAuth2Credentials`
instance.
"""
serialized = credentials.to_json()
self._dictionary[self._key] = serialized | [
"def",
"locked_put",
"(",
"self",
",",
"credentials",
")",
":",
"serialized",
"=",
"credentials",
".",
"to_json",
"(",
")",
"self",
".",
"_dictionary",
"[",
"self",
".",
"_key",
"]",
"=",
"serialized"
] | [
52,
4
] | [
60,
48
] | python | en | ['en', 'en', 'en'] | True |
DictionaryStorage.locked_delete | (self) | Remove the credentials from the dictionary, if they exist. | Remove the credentials from the dictionary, if they exist. | def locked_delete(self):
"""Remove the credentials from the dictionary, if they exist."""
self._dictionary.pop(self._key, None) | [
"def",
"locked_delete",
"(",
"self",
")",
":",
"self",
".",
"_dictionary",
".",
"pop",
"(",
"self",
".",
"_key",
",",
"None",
")"
] | [
62,
4
] | [
64,
45
] | python | en | ['en', 'en', 'en'] | True |
TagMap.presentTypes | (self) | Return *TagSet* to ASN.1 type map present in callee *TagMap* | Return *TagSet* to ASN.1 type map present in callee *TagMap* | def presentTypes(self):
"""Return *TagSet* to ASN.1 type map present in callee *TagMap*"""
return self.__presentTypes | [
"def",
"presentTypes",
"(",
"self",
")",
":",
"return",
"self",
".",
"__presentTypes"
] | [
72,
4
] | [
74,
34
] | python | en | ['en', 'en', 'en'] | True |
TagMap.skipTypes | (self) | Return *TagSet* collection unconditionally absent in callee *TagMap* | Return *TagSet* collection unconditionally absent in callee *TagMap* | def skipTypes(self):
"""Return *TagSet* collection unconditionally absent in callee *TagMap*"""
return self.__skipTypes | [
"def",
"skipTypes",
"(",
"self",
")",
":",
"return",
"self",
".",
"__skipTypes"
] | [
77,
4
] | [
79,
31
] | python | en | ['en', 'en', 'en'] | True |
TagMap.defaultType | (self) | Return default ASN.1 type being returned for any missing *TagSet* | Return default ASN.1 type being returned for any missing *TagSet* | def defaultType(self):
"""Return default ASN.1 type being returned for any missing *TagSet*"""
return self.__defaultType | [
"def",
"defaultType",
"(",
"self",
")",
":",
"return",
"self",
".",
"__defaultType"
] | [
82,
4
] | [
84,
33
] | python | en | ['en', 'en', 'en'] | True |
describe_token | (token) | Returns a description of the token. | Returns a description of the token. | def describe_token(token):
"""Returns a description of the token."""
if token.type == 'name':
return token.value
return _describe_token_type(token.type) | [
"def",
"describe_token",
"(",
"token",
")",
":",
"if",
"token",
".",
"type",
"==",
"'name'",
":",
"return",
"token",
".",
"value",
"return",
"_describe_token_type",
"(",
"token",
".",
"type",
")"
] | [
170,
0
] | [
174,
43
] | python | en | ['en', 'gl', 'en'] | True |
describe_token_expr | (expr) | Like `describe_token` but for token expressions. | Like `describe_token` but for token expressions. | def describe_token_expr(expr):
"""Like `describe_token` but for token expressions."""
if ':' in expr:
type, value = expr.split(':', 1)
if type == 'name':
return value
else:
type = expr
return _describe_token_type(type) | [
"def",
"describe_token_expr",
"(",
"expr",
")",
":",
"if",
"':'",
"in",
"expr",
":",
"type",
",",
"value",
"=",
"expr",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"type",
"==",
"'name'",
":",
"return",
"value",
"else",
":",
"type",
"=",
"expr",
"return",
"_describe_token_type",
"(",
"type",
")"
] | [
177,
0
] | [
185,
37
] | python | en | ['en', 'en', 'en'] | True |
count_newlines | (value) | Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
| Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
| def count_newlines(value):
"""Count the number of newline characters in the string. This is
useful for extensions that filter a stream.
"""
return len(newline_re.findall(value)) | [
"def",
"count_newlines",
"(",
"value",
")",
":",
"return",
"len",
"(",
"newline_re",
".",
"findall",
"(",
"value",
")",
")"
] | [
188,
0
] | [
192,
41
] | python | en | ['en', 'en', 'en'] | True |
compile_rules | (environment) | Compiles all the rules from the environment into a list of rules. | Compiles all the rules from the environment into a list of rules. | def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(len(environment.comment_start_string), 'comment',
e(environment.comment_start_string)),
(len(environment.block_start_string), 'block',
e(environment.block_start_string)),
(len(environment.variable_start_string), 'variable',
e(environment.variable_start_string))
]
if environment.line_statement_prefix is not None:
rules.append((len(environment.line_statement_prefix), 'linestatement',
r'^[ \t\v]*' + e(environment.line_statement_prefix)))
if environment.line_comment_prefix is not None:
rules.append((len(environment.line_comment_prefix), 'linecomment',
r'(?:^|(?<=\S))[^\S\r\n]*' +
e(environment.line_comment_prefix)))
return [x[1:] for x in sorted(rules, reverse=True)] | [
"def",
"compile_rules",
"(",
"environment",
")",
":",
"e",
"=",
"re",
".",
"escape",
"rules",
"=",
"[",
"(",
"len",
"(",
"environment",
".",
"comment_start_string",
")",
",",
"'comment'",
",",
"e",
"(",
"environment",
".",
"comment_start_string",
")",
")",
",",
"(",
"len",
"(",
"environment",
".",
"block_start_string",
")",
",",
"'block'",
",",
"e",
"(",
"environment",
".",
"block_start_string",
")",
")",
",",
"(",
"len",
"(",
"environment",
".",
"variable_start_string",
")",
",",
"'variable'",
",",
"e",
"(",
"environment",
".",
"variable_start_string",
")",
")",
"]",
"if",
"environment",
".",
"line_statement_prefix",
"is",
"not",
"None",
":",
"rules",
".",
"append",
"(",
"(",
"len",
"(",
"environment",
".",
"line_statement_prefix",
")",
",",
"'linestatement'",
",",
"r'^[ \\t\\v]*'",
"+",
"e",
"(",
"environment",
".",
"line_statement_prefix",
")",
")",
")",
"if",
"environment",
".",
"line_comment_prefix",
"is",
"not",
"None",
":",
"rules",
".",
"append",
"(",
"(",
"len",
"(",
"environment",
".",
"line_comment_prefix",
")",
",",
"'linecomment'",
",",
"r'(?:^|(?<=\\S))[^\\S\\r\\n]*'",
"+",
"e",
"(",
"environment",
".",
"line_comment_prefix",
")",
")",
")",
"return",
"[",
"x",
"[",
"1",
":",
"]",
"for",
"x",
"in",
"sorted",
"(",
"rules",
",",
"reverse",
"=",
"True",
")",
"]"
] | [
195,
0
] | [
215,
55
] | python | en | ['en', 'en', 'en'] | True |
get_lexer | (environment) | Return a lexer which is probably cached. | Return a lexer which is probably cached. | def get_lexer(environment):
"""Return a lexer which is probably cached."""
key = (environment.block_start_string,
environment.block_end_string,
environment.variable_start_string,
environment.variable_end_string,
environment.comment_start_string,
environment.comment_end_string,
environment.line_statement_prefix,
environment.line_comment_prefix,
environment.trim_blocks,
environment.lstrip_blocks,
environment.newline_sequence,
environment.keep_trailing_newline)
lexer = _lexer_cache.get(key)
if lexer is None:
lexer = Lexer(environment)
_lexer_cache[key] = lexer
return lexer | [
"def",
"get_lexer",
"(",
"environment",
")",
":",
"key",
"=",
"(",
"environment",
".",
"block_start_string",
",",
"environment",
".",
"block_end_string",
",",
"environment",
".",
"variable_start_string",
",",
"environment",
".",
"variable_end_string",
",",
"environment",
".",
"comment_start_string",
",",
"environment",
".",
"comment_end_string",
",",
"environment",
".",
"line_statement_prefix",
",",
"environment",
".",
"line_comment_prefix",
",",
"environment",
".",
"trim_blocks",
",",
"environment",
".",
"lstrip_blocks",
",",
"environment",
".",
"newline_sequence",
",",
"environment",
".",
"keep_trailing_newline",
")",
"lexer",
"=",
"_lexer_cache",
".",
"get",
"(",
"key",
")",
"if",
"lexer",
"is",
"None",
":",
"lexer",
"=",
"Lexer",
"(",
"environment",
")",
"_lexer_cache",
"[",
"key",
"]",
"=",
"lexer",
"return",
"lexer"
] | [
390,
0
] | [
408,
16
] | python | en | ['en', 'en', 'en'] | True |
Token.test | (self, expr) | Test a token against a token expression. This can either be a
token type or ``'token_type:token_value'``. This can only test
against string values and types.
| Test a token against a token expression. This can either be a
token type or ``'token_type:token_value'``. This can only test
against string values and types.
| def test(self, expr):
"""Test a token against a token expression. This can either be a
token type or ``'token_type:token_value'``. This can only test
against string values and types.
"""
# here we do a regular string equality check as test_any is usually
# passed an iterable of not interned strings.
if self.type == expr:
return True
elif ':' in expr:
return expr.split(':', 1) == [self.type, self.value]
return False | [
"def",
"test",
"(",
"self",
",",
"expr",
")",
":",
"# here we do a regular string equality check as test_any is usually",
"# passed an iterable of not interned strings.",
"if",
"self",
".",
"type",
"==",
"expr",
":",
"return",
"True",
"elif",
"':'",
"in",
"expr",
":",
"return",
"expr",
".",
"split",
"(",
"':'",
",",
"1",
")",
"==",
"[",
"self",
".",
"type",
",",
"self",
".",
"value",
"]",
"return",
"False"
] | [
246,
4
] | [
257,
20
] | python | en | ['en', 'en', 'en'] | True |
Token.test_any | (self, *iterable) | Test against multiple token expressions. | Test against multiple token expressions. | def test_any(self, *iterable):
"""Test against multiple token expressions."""
for expr in iterable:
if self.test(expr):
return True
return False | [
"def",
"test_any",
"(",
"self",
",",
"*",
"iterable",
")",
":",
"for",
"expr",
"in",
"iterable",
":",
"if",
"self",
".",
"test",
"(",
"expr",
")",
":",
"return",
"True",
"return",
"False"
] | [
259,
4
] | [
264,
20
] | python | en | ['nl', 'en', 'en'] | True |
Lexer._normalize_newlines | (self, value) | Called for strings and template data to normalize it to unicode. | Called for strings and template data to normalize it to unicode. | def _normalize_newlines(self, value):
"""Called for strings and template data to normalize it to unicode."""
return newline_re.sub(self.newline_sequence, value) | [
"def",
"_normalize_newlines",
"(",
"self",
",",
"value",
")",
":",
"return",
"newline_re",
".",
"sub",
"(",
"self",
".",
"newline_sequence",
",",
"value",
")"
] | [
547,
4
] | [
549,
59
] | python | en | ['en', 'en', 'en'] | True |
Lexer.tokenize | (self, source, name=None, filename=None, state=None) | Calls tokeniter + tokenize and wraps it in a token stream.
| Calls tokeniter + tokenize and wraps it in a token stream.
| def tokenize(self, source, name=None, filename=None, state=None):
"""Calls tokeniter + tokenize and wraps it in a token stream.
"""
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename) | [
"def",
"tokenize",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"stream",
"=",
"self",
".",
"tokeniter",
"(",
"source",
",",
"name",
",",
"filename",
",",
"state",
")",
"return",
"TokenStream",
"(",
"self",
".",
"wrap",
"(",
"stream",
",",
"name",
",",
"filename",
")",
",",
"name",
",",
"filename",
")"
] | [
551,
4
] | [
555,
77
] | python | en | ['en', 'en', 'en'] | True |
Lexer.wrap | (self, stream, name=None, filename=None) | This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
| This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
| def wrap(self, stream, name=None, filename=None):
"""This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value.
"""
for lineno, token, value in stream:
if token in ignored_tokens:
continue
elif token == 'linestatement_begin':
token = 'block_begin'
elif token == 'linestatement_end':
token = 'block_end'
# we are not interested in those tokens in the parser
elif token in ('raw_begin', 'raw_end'):
continue
elif token == 'data':
value = self._normalize_newlines(value)
elif token == 'keyword':
token = value
elif token == 'name':
value = str(value)
if check_ident and not value.isidentifier():
raise TemplateSyntaxError(
'Invalid character in identifier',
lineno, name, filename)
elif token == 'string':
# try to unescape string
try:
value = self._normalize_newlines(value[1:-1]) \
.encode('ascii', 'backslashreplace') \
.decode('unicode-escape')
except Exception as e:
msg = str(e).split(':')[-1].strip()
raise TemplateSyntaxError(msg, lineno, name, filename)
elif token == 'integer':
value = int(value)
elif token == 'float':
value = float(value)
elif token == 'operator':
token = operators[value]
yield Token(lineno, token, value) | [
"def",
"wrap",
"(",
"self",
",",
"stream",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"for",
"lineno",
",",
"token",
",",
"value",
"in",
"stream",
":",
"if",
"token",
"in",
"ignored_tokens",
":",
"continue",
"elif",
"token",
"==",
"'linestatement_begin'",
":",
"token",
"=",
"'block_begin'",
"elif",
"token",
"==",
"'linestatement_end'",
":",
"token",
"=",
"'block_end'",
"# we are not interested in those tokens in the parser",
"elif",
"token",
"in",
"(",
"'raw_begin'",
",",
"'raw_end'",
")",
":",
"continue",
"elif",
"token",
"==",
"'data'",
":",
"value",
"=",
"self",
".",
"_normalize_newlines",
"(",
"value",
")",
"elif",
"token",
"==",
"'keyword'",
":",
"token",
"=",
"value",
"elif",
"token",
"==",
"'name'",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"check_ident",
"and",
"not",
"value",
".",
"isidentifier",
"(",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"'Invalid character in identifier'",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"elif",
"token",
"==",
"'string'",
":",
"# try to unescape string",
"try",
":",
"value",
"=",
"self",
".",
"_normalize_newlines",
"(",
"value",
"[",
"1",
":",
"-",
"1",
"]",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'backslashreplace'",
")",
".",
"decode",
"(",
"'unicode-escape'",
")",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"str",
"(",
"e",
")",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"raise",
"TemplateSyntaxError",
"(",
"msg",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"elif",
"token",
"==",
"'integer'",
":",
"value",
"=",
"int",
"(",
"value",
")",
"elif",
"token",
"==",
"'float'",
":",
"value",
"=",
"float",
"(",
"value",
")",
"elif",
"token",
"==",
"'operator'",
":",
"token",
"=",
"operators",
"[",
"value",
"]",
"yield",
"Token",
"(",
"lineno",
",",
"token",
",",
"value",
")"
] | [
557,
4
] | [
596,
45
] | python | en | ['en', 'en', 'en'] | True |
Lexer.tokeniter | (self, source, name, filename=None, state=None) | This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template.
| This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template.
| def tokeniter(self, source, name, filename=None, state=None):
"""This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template.
"""
source = text_type(source)
lines = source.splitlines()
if self.keep_trailing_newline and source:
for newline in ('\r\n', '\r', '\n'):
if source.endswith(newline):
lines.append('')
break
source = '\n'.join(lines)
pos = 0
lineno = 1
stack = ['root']
if state is not None and state != 'root':
assert state in ('variable', 'block'), 'invalid state'
stack.append(state + '_begin')
else:
state = 'root'
statetokens = self.rules[stack[-1]]
source_length = len(source)
balancing_stack = []
while 1:
# tokenizer loop
for regex, tokens, new_state in statetokens:
m = regex.match(source, pos)
# if no match we try again with the next rule
if m is None:
continue
# we only match blocks and variables if braces / parentheses
# are balanced. continue parsing with the lower rule which
# is the operator rule. do this only if the end tags look
# like operators
if balancing_stack and \
tokens in ('variable_end', 'block_end',
'linestatement_end'):
continue
# tuples support more options
if isinstance(tokens, tuple):
for idx, token in enumerate(tokens):
# failure group
if token.__class__ is Failure:
raise token(lineno, filename)
# bygroup is a bit more complex, in that case we
# yield for the current token the first named
# group that matched
elif token == '#bygroup':
for key, value in iteritems(m.groupdict()):
if value is not None:
yield lineno, key, value
lineno += value.count('\n')
break
else:
raise RuntimeError('%r wanted to resolve '
'the token dynamically'
' but no group matched'
% regex)
# normal group
else:
data = m.group(idx + 1)
if data or token not in ignore_if_empty:
yield lineno, token, data
lineno += data.count('\n')
# strings as token just are yielded as it.
else:
data = m.group()
# update brace/parentheses balance
if tokens == 'operator':
if data == '{':
balancing_stack.append('}')
elif data == '(':
balancing_stack.append(')')
elif data == '[':
balancing_stack.append(']')
elif data in ('}', ')', ']'):
if not balancing_stack:
raise TemplateSyntaxError('unexpected \'%s\'' %
data, lineno, name,
filename)
expected_op = balancing_stack.pop()
if expected_op != data:
raise TemplateSyntaxError('unexpected \'%s\', '
'expected \'%s\'' %
(data, expected_op),
lineno, name,
filename)
# yield items
if data or tokens not in ignore_if_empty:
yield lineno, tokens, data
lineno += data.count('\n')
# fetch new position into new variable so that we can check
# if there is a internal parsing error which would result
# in an infinite loop
pos2 = m.end()
# handle state changes
if new_state is not None:
# remove the uppermost state
if new_state == '#pop':
stack.pop()
# resolve the new state by group checking
elif new_state == '#bygroup':
for key, value in iteritems(m.groupdict()):
if value is not None:
stack.append(key)
break
else:
raise RuntimeError('%r wanted to resolve the '
'new state dynamically but'
' no group matched' %
regex)
# direct state name given
else:
stack.append(new_state)
statetokens = self.rules[stack[-1]]
# we are still at the same position and no stack change.
# this means a loop without break condition, avoid that and
# raise error
elif pos2 == pos:
raise RuntimeError('%r yielded empty string without '
'stack change' % regex)
# publish new function and start again
pos = pos2
break
# if loop terminated without break we haven't found a single match
# either we are at the end of the file or we have a problem
else:
# end of text
if pos >= source_length:
return
# something went wrong
raise TemplateSyntaxError('unexpected char %r at %d' %
(source[pos], pos), lineno,
name, filename) | [
"def",
"tokeniter",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"source",
"=",
"text_type",
"(",
"source",
")",
"lines",
"=",
"source",
".",
"splitlines",
"(",
")",
"if",
"self",
".",
"keep_trailing_newline",
"and",
"source",
":",
"for",
"newline",
"in",
"(",
"'\\r\\n'",
",",
"'\\r'",
",",
"'\\n'",
")",
":",
"if",
"source",
".",
"endswith",
"(",
"newline",
")",
":",
"lines",
".",
"append",
"(",
"''",
")",
"break",
"source",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"pos",
"=",
"0",
"lineno",
"=",
"1",
"stack",
"=",
"[",
"'root'",
"]",
"if",
"state",
"is",
"not",
"None",
"and",
"state",
"!=",
"'root'",
":",
"assert",
"state",
"in",
"(",
"'variable'",
",",
"'block'",
")",
",",
"'invalid state'",
"stack",
".",
"append",
"(",
"state",
"+",
"'_begin'",
")",
"else",
":",
"state",
"=",
"'root'",
"statetokens",
"=",
"self",
".",
"rules",
"[",
"stack",
"[",
"-",
"1",
"]",
"]",
"source_length",
"=",
"len",
"(",
"source",
")",
"balancing_stack",
"=",
"[",
"]",
"while",
"1",
":",
"# tokenizer loop",
"for",
"regex",
",",
"tokens",
",",
"new_state",
"in",
"statetokens",
":",
"m",
"=",
"regex",
".",
"match",
"(",
"source",
",",
"pos",
")",
"# if no match we try again with the next rule",
"if",
"m",
"is",
"None",
":",
"continue",
"# we only match blocks and variables if braces / parentheses",
"# are balanced. continue parsing with the lower rule which",
"# is the operator rule. do this only if the end tags look",
"# like operators",
"if",
"balancing_stack",
"and",
"tokens",
"in",
"(",
"'variable_end'",
",",
"'block_end'",
",",
"'linestatement_end'",
")",
":",
"continue",
"# tuples support more options",
"if",
"isinstance",
"(",
"tokens",
",",
"tuple",
")",
":",
"for",
"idx",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"# failure group",
"if",
"token",
".",
"__class__",
"is",
"Failure",
":",
"raise",
"token",
"(",
"lineno",
",",
"filename",
")",
"# bygroup is a bit more complex, in that case we",
"# yield for the current token the first named",
"# group that matched",
"elif",
"token",
"==",
"'#bygroup'",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"m",
".",
"groupdict",
"(",
")",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"yield",
"lineno",
",",
"key",
",",
"value",
"lineno",
"+=",
"value",
".",
"count",
"(",
"'\\n'",
")",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"'%r wanted to resolve '",
"'the token dynamically'",
"' but no group matched'",
"%",
"regex",
")",
"# normal group",
"else",
":",
"data",
"=",
"m",
".",
"group",
"(",
"idx",
"+",
"1",
")",
"if",
"data",
"or",
"token",
"not",
"in",
"ignore_if_empty",
":",
"yield",
"lineno",
",",
"token",
",",
"data",
"lineno",
"+=",
"data",
".",
"count",
"(",
"'\\n'",
")",
"# strings as token just are yielded as it.",
"else",
":",
"data",
"=",
"m",
".",
"group",
"(",
")",
"# update brace/parentheses balance",
"if",
"tokens",
"==",
"'operator'",
":",
"if",
"data",
"==",
"'{'",
":",
"balancing_stack",
".",
"append",
"(",
"'}'",
")",
"elif",
"data",
"==",
"'('",
":",
"balancing_stack",
".",
"append",
"(",
"')'",
")",
"elif",
"data",
"==",
"'['",
":",
"balancing_stack",
".",
"append",
"(",
"']'",
")",
"elif",
"data",
"in",
"(",
"'}'",
",",
"')'",
",",
"']'",
")",
":",
"if",
"not",
"balancing_stack",
":",
"raise",
"TemplateSyntaxError",
"(",
"'unexpected \\'%s\\''",
"%",
"data",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"expected_op",
"=",
"balancing_stack",
".",
"pop",
"(",
")",
"if",
"expected_op",
"!=",
"data",
":",
"raise",
"TemplateSyntaxError",
"(",
"'unexpected \\'%s\\', '",
"'expected \\'%s\\''",
"%",
"(",
"data",
",",
"expected_op",
")",
",",
"lineno",
",",
"name",
",",
"filename",
")",
"# yield items",
"if",
"data",
"or",
"tokens",
"not",
"in",
"ignore_if_empty",
":",
"yield",
"lineno",
",",
"tokens",
",",
"data",
"lineno",
"+=",
"data",
".",
"count",
"(",
"'\\n'",
")",
"# fetch new position into new variable so that we can check",
"# if there is a internal parsing error which would result",
"# in an infinite loop",
"pos2",
"=",
"m",
".",
"end",
"(",
")",
"# handle state changes",
"if",
"new_state",
"is",
"not",
"None",
":",
"# remove the uppermost state",
"if",
"new_state",
"==",
"'#pop'",
":",
"stack",
".",
"pop",
"(",
")",
"# resolve the new state by group checking",
"elif",
"new_state",
"==",
"'#bygroup'",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"m",
".",
"groupdict",
"(",
")",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"stack",
".",
"append",
"(",
"key",
")",
"break",
"else",
":",
"raise",
"RuntimeError",
"(",
"'%r wanted to resolve the '",
"'new state dynamically but'",
"' no group matched'",
"%",
"regex",
")",
"# direct state name given",
"else",
":",
"stack",
".",
"append",
"(",
"new_state",
")",
"statetokens",
"=",
"self",
".",
"rules",
"[",
"stack",
"[",
"-",
"1",
"]",
"]",
"# we are still at the same position and no stack change.",
"# this means a loop without break condition, avoid that and",
"# raise error",
"elif",
"pos2",
"==",
"pos",
":",
"raise",
"RuntimeError",
"(",
"'%r yielded empty string without '",
"'stack change'",
"%",
"regex",
")",
"# publish new function and start again",
"pos",
"=",
"pos2",
"break",
"# if loop terminated without break we haven't found a single match",
"# either we are at the end of the file or we have a problem",
"else",
":",
"# end of text",
"if",
"pos",
">=",
"source_length",
":",
"return",
"# something went wrong",
"raise",
"TemplateSyntaxError",
"(",
"'unexpected char %r at %d'",
"%",
"(",
"source",
"[",
"pos",
"]",
",",
"pos",
")",
",",
"lineno",
",",
"name",
",",
"filename",
")"
] | [
598,
4
] | [
738,
57
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.__init__ | (
self,
*,
host: str = "monitoring.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) | Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for the grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure a mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
| Instantiate the transport. | def __init__(
self,
*,
host: str = "monitoring.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for the grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure a mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
# Ignore credentials if a channel was passed.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
)
if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
self._host,
credentials=self._credentials,
credentials_file=credentials_file,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Wrap messages. This must be done after self._grpc_channel exists
self._prep_wrapped_messages(client_info) | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"host",
":",
"str",
"=",
"\"monitoring.googleapis.com\"",
",",
"credentials",
":",
"ga_credentials",
".",
"Credentials",
"=",
"None",
",",
"credentials_file",
":",
"str",
"=",
"None",
",",
"scopes",
":",
"Sequence",
"[",
"str",
"]",
"=",
"None",
",",
"channel",
":",
"grpc",
".",
"Channel",
"=",
"None",
",",
"api_mtls_endpoint",
":",
"str",
"=",
"None",
",",
"client_cert_source",
":",
"Callable",
"[",
"[",
"]",
",",
"Tuple",
"[",
"bytes",
",",
"bytes",
"]",
"]",
"=",
"None",
",",
"ssl_channel_credentials",
":",
"grpc",
".",
"ChannelCredentials",
"=",
"None",
",",
"client_cert_source_for_mtls",
":",
"Callable",
"[",
"[",
"]",
",",
"Tuple",
"[",
"bytes",
",",
"bytes",
"]",
"]",
"=",
"None",
",",
"quota_project_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"client_info",
":",
"gapic_v1",
".",
"client_info",
".",
"ClientInfo",
"=",
"DEFAULT_CLIENT_INFO",
",",
"always_use_jwt_access",
":",
"Optional",
"[",
"bool",
"]",
"=",
"False",
",",
")",
"->",
"None",
":",
"self",
".",
"_grpc_channel",
"=",
"None",
"self",
".",
"_ssl_channel_credentials",
"=",
"ssl_channel_credentials",
"self",
".",
"_stubs",
":",
"Dict",
"[",
"str",
",",
"Callable",
"]",
"=",
"{",
"}",
"if",
"api_mtls_endpoint",
":",
"warnings",
".",
"warn",
"(",
"\"api_mtls_endpoint is deprecated\"",
",",
"DeprecationWarning",
")",
"if",
"client_cert_source",
":",
"warnings",
".",
"warn",
"(",
"\"client_cert_source is deprecated\"",
",",
"DeprecationWarning",
")",
"if",
"channel",
":",
"# Ignore credentials if a channel was passed.",
"credentials",
"=",
"False",
"# If a channel was explicitly provided, set it.",
"self",
".",
"_grpc_channel",
"=",
"channel",
"self",
".",
"_ssl_channel_credentials",
"=",
"None",
"else",
":",
"if",
"api_mtls_endpoint",
":",
"host",
"=",
"api_mtls_endpoint",
"# Create SSL credentials with client_cert_source or application",
"# default SSL credentials.",
"if",
"client_cert_source",
":",
"cert",
",",
"key",
"=",
"client_cert_source",
"(",
")",
"self",
".",
"_ssl_channel_credentials",
"=",
"grpc",
".",
"ssl_channel_credentials",
"(",
"certificate_chain",
"=",
"cert",
",",
"private_key",
"=",
"key",
")",
"else",
":",
"self",
".",
"_ssl_channel_credentials",
"=",
"SslCredentials",
"(",
")",
".",
"ssl_credentials",
"else",
":",
"if",
"client_cert_source_for_mtls",
"and",
"not",
"ssl_channel_credentials",
":",
"cert",
",",
"key",
"=",
"client_cert_source_for_mtls",
"(",
")",
"self",
".",
"_ssl_channel_credentials",
"=",
"grpc",
".",
"ssl_channel_credentials",
"(",
"certificate_chain",
"=",
"cert",
",",
"private_key",
"=",
"key",
")",
"# The base transport sets the host, credentials and scopes",
"super",
"(",
")",
".",
"__init__",
"(",
"host",
"=",
"host",
",",
"credentials",
"=",
"credentials",
",",
"credentials_file",
"=",
"credentials_file",
",",
"scopes",
"=",
"scopes",
",",
"quota_project_id",
"=",
"quota_project_id",
",",
"client_info",
"=",
"client_info",
",",
"always_use_jwt_access",
"=",
"always_use_jwt_access",
",",
")",
"if",
"not",
"self",
".",
"_grpc_channel",
":",
"self",
".",
"_grpc_channel",
"=",
"type",
"(",
"self",
")",
".",
"create_channel",
"(",
"self",
".",
"_host",
",",
"credentials",
"=",
"self",
".",
"_credentials",
",",
"credentials_file",
"=",
"credentials_file",
",",
"scopes",
"=",
"self",
".",
"_scopes",
",",
"ssl_credentials",
"=",
"self",
".",
"_ssl_channel_credentials",
",",
"quota_project_id",
"=",
"quota_project_id",
",",
"options",
"=",
"[",
"(",
"\"grpc.max_send_message_length\"",
",",
"-",
"1",
")",
",",
"(",
"\"grpc.max_receive_message_length\"",
",",
"-",
"1",
")",
",",
"]",
",",
")",
"# Wrap messages. This must be done after self._grpc_channel exists",
"self",
".",
"_prep_wrapped_messages",
"(",
"client_info",
")"
] | [
48,
4
] | [
175,
48
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.create_channel | (
cls,
host: str = "monitoring.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) | Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
| Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object. | def create_channel(
cls,
host: str = "monitoring.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
) | [
"def",
"create_channel",
"(",
"cls",
",",
"host",
":",
"str",
"=",
"\"monitoring.googleapis.com\"",
",",
"credentials",
":",
"ga_credentials",
".",
"Credentials",
"=",
"None",
",",
"credentials_file",
":",
"str",
"=",
"None",
",",
"scopes",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"quota_project_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"grpc",
".",
"Channel",
":",
"return",
"grpc_helpers",
".",
"create_channel",
"(",
"host",
",",
"credentials",
"=",
"credentials",
",",
"credentials_file",
"=",
"credentials_file",
",",
"quota_project_id",
"=",
"quota_project_id",
",",
"default_scopes",
"=",
"cls",
".",
"AUTH_SCOPES",
",",
"scopes",
"=",
"scopes",
",",
"default_host",
"=",
"cls",
".",
"DEFAULT_HOST",
",",
"*",
"*",
"kwargs",
",",
")"
] | [
178,
4
] | [
222,
9
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.grpc_channel | (self) | Return the channel designed to connect to this service.
| Return the channel designed to connect to this service.
| def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel | [
"def",
"grpc_channel",
"(",
"self",
")",
"->",
"grpc",
".",
"Channel",
":",
"return",
"self",
".",
"_grpc_channel"
] | [
225,
4
] | [
228,
33
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.create_dashboard | (
self,
) | r"""Return a callable for the create dashboard method over gRPC.
Creates a new custom dashboard. For examples on how you can use
this API to create dashboards, see `Managing dashboards by
API <https://cloud.google.com/monitoring/dashboards/api-dashboard>`__.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information about
permissions, see `Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.CreateDashboardRequest],
~.Dashboard]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the create dashboard method over gRPC. | def create_dashboard(
self,
) -> Callable[[dashboards_service.CreateDashboardRequest], dashboard.Dashboard]:
r"""Return a callable for the create dashboard method over gRPC.
Creates a new custom dashboard. For examples on how you can use
this API to create dashboards, see `Managing dashboards by
API <https://cloud.google.com/monitoring/dashboards/api-dashboard>`__.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information about
permissions, see `Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.CreateDashboardRequest],
~.Dashboard]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_dashboard" not in self._stubs:
self._stubs["create_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard",
request_serializer=dashboards_service.CreateDashboardRequest.serialize,
response_deserializer=dashboard.Dashboard.deserialize,
)
return self._stubs["create_dashboard"] | [
"def",
"create_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"CreateDashboardRequest",
"]",
",",
"dashboard",
".",
"Dashboard",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"create_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"create_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/CreateDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"CreateDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboard",
".",
"Dashboard",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"create_dashboard\"",
"]"
] | [
231,
4
] | [
260,
46
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.list_dashboards | (
self,
) | r"""Return a callable for the list dashboards method over gRPC.
Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.ListDashboardsRequest],
~.ListDashboardsResponse]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the list dashboards method over gRPC. | def list_dashboards(
self,
) -> Callable[
[dashboards_service.ListDashboardsRequest],
dashboards_service.ListDashboardsResponse,
]:
r"""Return a callable for the list dashboards method over gRPC.
Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.ListDashboardsRequest],
~.ListDashboardsResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_dashboards" not in self._stubs:
self._stubs["list_dashboards"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/ListDashboards",
request_serializer=dashboards_service.ListDashboardsRequest.serialize,
response_deserializer=dashboards_service.ListDashboardsResponse.deserialize,
)
return self._stubs["list_dashboards"] | [
"def",
"list_dashboards",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"ListDashboardsRequest",
"]",
",",
"dashboards_service",
".",
"ListDashboardsResponse",
",",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"list_dashboards\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"list_dashboards\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/ListDashboards\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"ListDashboardsRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboards_service",
".",
"ListDashboardsResponse",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"list_dashboards\"",
"]"
] | [
263,
4
] | [
294,
45
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.get_dashboard | (
self,
) | r"""Return a callable for the get dashboard method over gRPC.
Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.GetDashboardRequest],
~.Dashboard]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the get dashboard method over gRPC. | def get_dashboard(
self,
) -> Callable[[dashboards_service.GetDashboardRequest], dashboard.Dashboard]:
r"""Return a callable for the get dashboard method over gRPC.
Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.GetDashboardRequest],
~.Dashboard]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_dashboard" not in self._stubs:
self._stubs["get_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/GetDashboard",
request_serializer=dashboards_service.GetDashboardRequest.serialize,
response_deserializer=dashboard.Dashboard.deserialize,
)
return self._stubs["get_dashboard"] | [
"def",
"get_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"GetDashboardRequest",
"]",
",",
"dashboard",
".",
"Dashboard",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"get_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"get_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/GetDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"GetDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboard",
".",
"Dashboard",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"get_dashboard\"",
"]"
] | [
297,
4
] | [
325,
43
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.delete_dashboard | (
self,
) | r"""Return a callable for the delete dashboard method over gRPC.
Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.DeleteDashboardRequest],
~.Empty]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the delete dashboard method over gRPC. | def delete_dashboard(
self,
) -> Callable[[dashboards_service.DeleteDashboardRequest], empty_pb2.Empty]:
r"""Return a callable for the delete dashboard method over gRPC.
Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.DeleteDashboardRequest],
~.Empty]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_dashboard" not in self._stubs:
self._stubs["delete_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard",
request_serializer=dashboards_service.DeleteDashboardRequest.serialize,
response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs["delete_dashboard"] | [
"def",
"delete_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"DeleteDashboardRequest",
"]",
",",
"empty_pb2",
".",
"Empty",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"delete_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"delete_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/DeleteDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"DeleteDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"empty_pb2",
".",
"Empty",
".",
"FromString",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"delete_dashboard\"",
"]"
] | [
328,
4
] | [
356,
46
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceGrpcTransport.update_dashboard | (
self,
) | r"""Return a callable for the update dashboard method over gRPC.
Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.UpdateDashboardRequest],
~.Dashboard]:
A function that, when called, will call the underlying RPC
on the server.
| r"""Return a callable for the update dashboard method over gRPC. | def update_dashboard(
self,
) -> Callable[[dashboards_service.UpdateDashboardRequest], dashboard.Dashboard]:
r"""Return a callable for the update dashboard method over gRPC.
Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Cloud Identity and Access
Management <https://cloud.google.com/iam>`__.
Returns:
Callable[[~.UpdateDashboardRequest],
~.Dashboard]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_dashboard" not in self._stubs:
self._stubs["update_dashboard"] = self.grpc_channel.unary_unary(
"/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard",
request_serializer=dashboards_service.UpdateDashboardRequest.serialize,
response_deserializer=dashboard.Dashboard.deserialize,
)
return self._stubs["update_dashboard"] | [
"def",
"update_dashboard",
"(",
"self",
",",
")",
"->",
"Callable",
"[",
"[",
"dashboards_service",
".",
"UpdateDashboardRequest",
"]",
",",
"dashboard",
".",
"Dashboard",
"]",
":",
"# Generate a \"stub function\" on-the-fly which will actually make",
"# the request.",
"# gRPC handles serialization and deserialization, so we just need",
"# to pass in the functions for each.",
"if",
"\"update_dashboard\"",
"not",
"in",
"self",
".",
"_stubs",
":",
"self",
".",
"_stubs",
"[",
"\"update_dashboard\"",
"]",
"=",
"self",
".",
"grpc_channel",
".",
"unary_unary",
"(",
"\"/google.monitoring.dashboard.v1.DashboardsService/UpdateDashboard\"",
",",
"request_serializer",
"=",
"dashboards_service",
".",
"UpdateDashboardRequest",
".",
"serialize",
",",
"response_deserializer",
"=",
"dashboard",
".",
"Dashboard",
".",
"deserialize",
",",
")",
"return",
"self",
".",
"_stubs",
"[",
"\"update_dashboard\"",
"]"
] | [
359,
4
] | [
387,
46
] | python | en | ['en', 'en', 'en'] | True |
write_to_stdout | (data) | Writes bytes to stdout
:type data: bytes
| Writes bytes to stdout | def write_to_stdout(data):
"""Writes bytes to stdout
:type data: bytes
"""
if PY2:
sys.stdout.write(data)
else:
# On Py3 we must use the buffer interface to write bytes.
sys.stdout.buffer.write(data) | [
"def",
"write_to_stdout",
"(",
"data",
")",
":",
"if",
"PY2",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"data",
")",
"else",
":",
"# On Py3 we must use the buffer interface to write bytes.",
"sys",
".",
"stdout",
".",
"buffer",
".",
"write",
"(",
"data",
")"
] | [
52,
0
] | [
61,
37
] | python | en | ['en', 'el-Latn', 'en'] | True |
is_bytes | (obj) |
Determines whether the given value is a byte string.
:param obj:
The value to test.
:returns:
``True`` if ``value`` is a byte string; ``False`` otherwise.
|
Determines whether the given value is a byte string. | def is_bytes(obj):
"""
Determines whether the given value is a byte string.
:param obj:
The value to test.
:returns:
``True`` if ``value`` is a byte string; ``False`` otherwise.
"""
return isinstance(obj, bytes) | [
"def",
"is_bytes",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"bytes",
")"
] | [
64,
0
] | [
73,
33
] | python | en | ['en', 'error', 'th'] | False |
is_integer | (obj) |
Determines whether the given value is an integer.
:param obj:
The value to test.
:returns:
``True`` if ``value`` is an integer; ``False`` otherwise.
|
Determines whether the given value is an integer. | def is_integer(obj):
"""
Determines whether the given value is an integer.
:param obj:
The value to test.
:returns:
``True`` if ``value`` is an integer; ``False`` otherwise.
"""
return isinstance(obj, integer_types) | [
"def",
"is_integer",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"integer_types",
")"
] | [
76,
0
] | [
85,
41
] | python | en | ['en', 'error', 'th'] | False |
byte | (num) |
Converts a number between 0 and 255 (both inclusive) to a base-256 (byte)
representation.
Use it as a replacement for ``chr`` where you are expecting a byte
because this will work on all current versions of Python::
:param num:
An unsigned integer between 0 and 255 (both inclusive).
:returns:
A single byte.
|
Converts a number between 0 and 255 (both inclusive) to a base-256 (byte)
representation. | def byte(num):
"""
Converts a number between 0 and 255 (both inclusive) to a base-256 (byte)
representation.
Use it as a replacement for ``chr`` where you are expecting a byte
because this will work on all current versions of Python::
:param num:
An unsigned integer between 0 and 255 (both inclusive).
:returns:
A single byte.
"""
return pack("B", num) | [
"def",
"byte",
"(",
"num",
")",
":",
"return",
"pack",
"(",
"\"B\"",
",",
"num",
")"
] | [
88,
0
] | [
101,
25
] | python | en | ['en', 'error', 'th'] | False |
xor_bytes | (b1, b2) |
Returns the bitwise XOR result between two bytes objects, b1 ^ b2.
Bitwise XOR operation is commutative, so order of parameters doesn't
generate different results. If parameters have different length, extra
length of the largest one is ignored.
:param b1:
First bytes object.
:param b2:
Second bytes object.
:returns:
Bytes object, result of XOR operation.
|
Returns the bitwise XOR result between two bytes objects, b1 ^ b2. | def xor_bytes(b1, b2):
"""
Returns the bitwise XOR result between two bytes objects, b1 ^ b2.
Bitwise XOR operation is commutative, so order of parameters doesn't
generate different results. If parameters have different length, extra
length of the largest one is ignored.
:param b1:
First bytes object.
:param b2:
Second bytes object.
:returns:
Bytes object, result of XOR operation.
"""
if PY2:
return ''.join(byte(ord(x) ^ ord(y)) for x, y in zip(b1, b2))
return bytes(x ^ y for x, y in zip(b1, b2)) | [
"def",
"xor_bytes",
"(",
"b1",
",",
"b2",
")",
":",
"if",
"PY2",
":",
"return",
"''",
".",
"join",
"(",
"byte",
"(",
"ord",
"(",
"x",
")",
"^",
"ord",
"(",
"y",
")",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"b1",
",",
"b2",
")",
")",
"return",
"bytes",
"(",
"x",
"^",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"b1",
",",
"b2",
")",
")"
] | [
104,
0
] | [
122,
47
] | python | en | ['en', 'error', 'th'] | False |
get_word_alignment | (num, force_arch=64,
_machine_word_size=MACHINE_WORD_SIZE) |
Returns alignment details for the given number based on the platform
Python is running on.
:param num:
Unsigned integral number.
:param force_arch:
If you don't want to use 64-bit unsigned chunks, set this to
anything other than 64. 32-bit chunks will be preferred then.
Default 64 will be used when on a 64-bit machine.
:param _machine_word_size:
(Internal) The machine word size used for alignment.
:returns:
4-tuple::
(word_bits, word_bytes,
max_uint, packing_format_type)
|
Returns alignment details for the given number based on the platform
Python is running on. | def get_word_alignment(num, force_arch=64,
_machine_word_size=MACHINE_WORD_SIZE):
"""
Returns alignment details for the given number based on the platform
Python is running on.
:param num:
Unsigned integral number.
:param force_arch:
If you don't want to use 64-bit unsigned chunks, set this to
anything other than 64. 32-bit chunks will be preferred then.
Default 64 will be used when on a 64-bit machine.
:param _machine_word_size:
(Internal) The machine word size used for alignment.
:returns:
4-tuple::
(word_bits, word_bytes,
max_uint, packing_format_type)
"""
max_uint64 = 0xffffffffffffffff
max_uint32 = 0xffffffff
max_uint16 = 0xffff
max_uint8 = 0xff
if force_arch == 64 and _machine_word_size >= 64 and num > max_uint32:
# 64-bit unsigned integer.
return 64, 8, max_uint64, "Q"
elif num > max_uint16:
# 32-bit unsigned integer
return 32, 4, max_uint32, "L"
elif num > max_uint8:
# 16-bit unsigned integer.
return 16, 2, max_uint16, "H"
else:
# 8-bit unsigned integer.
return 8, 1, max_uint8, "B" | [
"def",
"get_word_alignment",
"(",
"num",
",",
"force_arch",
"=",
"64",
",",
"_machine_word_size",
"=",
"MACHINE_WORD_SIZE",
")",
":",
"max_uint64",
"=",
"0xffffffffffffffff",
"max_uint32",
"=",
"0xffffffff",
"max_uint16",
"=",
"0xffff",
"max_uint8",
"=",
"0xff",
"if",
"force_arch",
"==",
"64",
"and",
"_machine_word_size",
">=",
"64",
"and",
"num",
">",
"max_uint32",
":",
"# 64-bit unsigned integer.",
"return",
"64",
",",
"8",
",",
"max_uint64",
",",
"\"Q\"",
"elif",
"num",
">",
"max_uint16",
":",
"# 32-bit unsigned integer",
"return",
"32",
",",
"4",
",",
"max_uint32",
",",
"\"L\"",
"elif",
"num",
">",
"max_uint8",
":",
"# 16-bit unsigned integer.",
"return",
"16",
",",
"2",
",",
"max_uint16",
",",
"\"H\"",
"else",
":",
"# 8-bit unsigned integer.",
"return",
"8",
",",
"1",
",",
"max_uint8",
",",
"\"B\""
] | [
125,
0
] | [
161,
35
] | python | en | ['en', 'error', 'th'] | False |
get_feature | (name) | Get an instance of a ``Features`` class by ``name`` (str). | Get an instance of a ``Features`` class by ``name`` (str). | def get_feature(name):
"""Get an instance of a ``Features`` class by ``name`` (str)."""
if name == 'css':
return CSSFeatures()
elif name == 'kohlschuetter':
return KohlschuetterFeatures()
elif name == 'readability':
return ReadabilityFeatures()
elif name == 'weninger':
return WeningerFeatures()
elif name == 'clustered_weninger':
return ClusteredWeningerFeatures()
else:
raise ValueError('invalid feature name: "{}"'.format(name)) | [
"def",
"get_feature",
"(",
"name",
")",
":",
"if",
"name",
"==",
"'css'",
":",
"return",
"CSSFeatures",
"(",
")",
"elif",
"name",
"==",
"'kohlschuetter'",
":",
"return",
"KohlschuetterFeatures",
"(",
")",
"elif",
"name",
"==",
"'readability'",
":",
"return",
"ReadabilityFeatures",
"(",
")",
"elif",
"name",
"==",
"'weninger'",
":",
"return",
"WeningerFeatures",
"(",
")",
"elif",
"name",
"==",
"'clustered_weninger'",
":",
"return",
"ClusteredWeningerFeatures",
"(",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'invalid feature name: \"{}\"'",
".",
"format",
"(",
"name",
")",
")"
] | [
7,
0
] | [
20,
67
] | python | en | ['en', 'en', 'en'] | True |
AuthorizationMixin.authorization | (self) | The `Authorization` object in parsed form. | The `Authorization` object in parsed form. | def authorization(self):
"""The `Authorization` object in parsed form."""
header = self.environ.get("HTTP_AUTHORIZATION")
return parse_authorization_header(header) | [
"def",
"authorization",
"(",
"self",
")",
":",
"header",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"\"HTTP_AUTHORIZATION\"",
")",
"return",
"parse_authorization_header",
"(",
"header",
")"
] | [
12,
4
] | [
15,
49
] | python | en | ['en', 'en', 'en'] | True |
WWWAuthenticateMixin.www_authenticate | (self) | The `WWW-Authenticate` header in a parsed form. | The `WWW-Authenticate` header in a parsed form. | def www_authenticate(self):
"""The `WWW-Authenticate` header in a parsed form."""
def on_update(www_auth):
if not www_auth and "www-authenticate" in self.headers:
del self.headers["www-authenticate"]
elif www_auth:
self.headers["WWW-Authenticate"] = www_auth.to_header()
header = self.headers.get("www-authenticate")
return parse_www_authenticate_header(header, on_update) | [
"def",
"www_authenticate",
"(",
"self",
")",
":",
"def",
"on_update",
"(",
"www_auth",
")",
":",
"if",
"not",
"www_auth",
"and",
"\"www-authenticate\"",
"in",
"self",
".",
"headers",
":",
"del",
"self",
".",
"headers",
"[",
"\"www-authenticate\"",
"]",
"elif",
"www_auth",
":",
"self",
".",
"headers",
"[",
"\"WWW-Authenticate\"",
"]",
"=",
"www_auth",
".",
"to_header",
"(",
")",
"header",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"www-authenticate\"",
")",
"return",
"parse_www_authenticate_header",
"(",
"header",
",",
"on_update",
")"
] | [
22,
4
] | [
32,
63
] | python | en | ['en', 'en', 'en'] | True |
DatabaseOperations.bulk_batch_size | (self, fields, objs) |
SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
999 variables per query.
If there's only a single field to insert, the limit is 500
(SQLITE_MAX_COMPOUND_SELECT).
|
SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
999 variables per query. | def bulk_batch_size(self, fields, objs):
"""
SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of
999 variables per query.
If there's only a single field to insert, the limit is 500
(SQLITE_MAX_COMPOUND_SELECT).
"""
if len(fields) == 1:
return 500
elif len(fields) > 1:
return self.connection.features.max_query_params // len(fields)
else:
return len(objs) | [
"def",
"bulk_batch_size",
"(",
"self",
",",
"fields",
",",
"objs",
")",
":",
"if",
"len",
"(",
"fields",
")",
"==",
"1",
":",
"return",
"500",
"elif",
"len",
"(",
"fields",
")",
">",
"1",
":",
"return",
"self",
".",
"connection",
".",
"features",
".",
"max_query_params",
"//",
"len",
"(",
"fields",
")",
"else",
":",
"return",
"len",
"(",
"objs",
")"
] | [
24,
4
] | [
37,
28
] | python | en | ['en', 'error', 'th'] | False |
DatabaseOperations.date_extract_sql | (self, lookup_type, field_name) |
Support EXTRACT with a user-defined function django_date_extract()
that's registered in connect(). Use single quotes because this is a
string and could otherwise cause a collision with a field name.
|
Support EXTRACT with a user-defined function django_date_extract()
that's registered in connect(). Use single quotes because this is a
string and could otherwise cause a collision with a field name.
| def date_extract_sql(self, lookup_type, field_name):
"""
Support EXTRACT with a user-defined function django_date_extract()
that's registered in connect(). Use single quotes because this is a
string and could otherwise cause a collision with a field name.
"""
return "django_date_extract('%s', %s)" % (lookup_type.lower(), field_name) | [
"def",
"date_extract_sql",
"(",
"self",
",",
"lookup_type",
",",
"field_name",
")",
":",
"return",
"\"django_date_extract('%s', %s)\"",
"%",
"(",
"lookup_type",
".",
"lower",
"(",
")",
",",
"field_name",
")"
] | [
67,
4
] | [
73,
82
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.