_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q249900 | PolymorphicAdminRawIdFix.formfield_for_foreignkey | train | def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
"""
Replicates the logic in ModelAdmin.forfield_for_foreignkey, replacing
the widget with the patched one above, initialising it with the child
admin site.
"""
db = kwargs.get('using')
if db_fie... | python | {
"resource": ""
} |
q249901 | wikipedia_slugify | train | def wikipedia_slugify(value, do_unidecode=False):
"""
Converts to ASCII via unidecode.
Converts spaces to underscore.
Removes characters that
aren't alphanumerics, underscores, | python | {
"resource": ""
} |
q249902 | ensure_unique | train | def ensure_unique(qs, field_name, value, exclude_id=None):
"""
Makes sure that `value` is unique on model.fieldname. And nonempty.
"""
orig = value
if not value:
value = "None"
for x in | python | {
"resource": ""
} |
q249903 | fix_line_breaks | train | def fix_line_breaks(s):
"""
Convert \r\n and \r to \n chars. Strip any leading or trailing whitespace
on each line. Remove blank lines.
"""
l = s.splitlines() | python | {
"resource": ""
} |
q249904 | update_json_analysis | train | def update_json_analysis(analysis, j):
"""
Step through the items in a piece of json, and update an analysis dict
with the values found.
"""
def _analyze_list(l, parent=""):
for v in l:
if isinstance(v, (dict, CaseInsensitiveDict)):
_analyze_json(v, parent=parent)... | python | {
"resource": ""
} |
q249905 | LayoutFieldMixin.add_missing_placeholders | train | def add_missing_placeholders(self):
"""
Add missing placeholders from templates. Return `True` if any missing
placeholders were created.
"""
content_type = ContentType.objects.get_for_model(self)
result = False
if self.layout:
for data in self.layout.g... | python | {
"resource": ""
} |
q249906 | ListableMixin.get_og_title | train | def get_og_title(self):
"""
return meta_title if exists otherwise fall back to title
"""
if | python | {
"resource": ""
} |
q249907 | GoogleMapMixin.get_map_data | train | def get_map_data(self):
"""
Returns a serializable data set describing the map location
"""
return {
'containerSelector': '#' + self.get_map_element_id(),
'center': self.map_center_description,
'marker': self.map_marker_description or self.map_center_... | python | {
"resource": ""
} |
q249908 | GoogleMapMixin.get_map_href | train | def get_map_href(self):
"""
Returns a link to an external view of the map
"""
if self.map_center_lat and self.map_center_long:
params = {
'll': '%s,%s' % (self.map_center_lat, self.map_center_long)
| python | {
"resource": ""
} |
q249909 | round_datetime | train | def round_datetime(when=None, precision=60, rounding=ROUND_NEAREST):
"""
Round a datetime object to a time that matches the given precision.
when (datetime), default now
The datetime object to be rounded.
precision (int, timedelta, str), default 60
The number of seconds... | python | {
"resource": ""
} |
q249910 | coerce_dt_awareness | train | def coerce_dt_awareness(date_or_datetime, tz=None, t=None):
"""
Coerce the given `datetime` or `date` object into a timezone-aware or
timezone-naive `datetime` result, depending on which is appropriate for
the project's settings.
"""
if isinstance(date_or_datetime, datetime):
dt = date_o... | python | {
"resource": ""
} |
q249911 | get_draft_secret_key | train | def get_draft_secret_key():
"""
Return the secret key used to generate draft mode HMACs. It will be
randomly generated on first access. Existing draft URLs can be invalidated
by deleting or updating the ``DRAFT_SECRET_KEY`` setting.
"""
# TODO: Per URL secret keys, so we can invalidate draft URL... | python | {
"resource": ""
} |
q249912 | get_draft_url | train | def get_draft_url(url):
"""
Return the given URL with a draft mode HMAC in its querystring.
"""
if verify_draft_url(url):
# Nothing to do. Already a valid draft URL.
return url
# Parse querystring and add draft mode HMAC.
url = urlparse.urlparse(url)
salt = get_random_string(... | python | {
"resource": ""
} |
q249913 | verify_draft_url | train | def verify_draft_url(url):
"""
Return ``True`` if the given URL has a valid draft mode HMAC in its
querystring.
"""
url = urlparse.urlparse(url)
# QueryDict requires a bytestring as its first argument
query = QueryDict(force_bytes(url.query))
# TODO Support legacy 'edit' | python | {
"resource": ""
} |
q249914 | contribute_to_class | train | def contribute_to_class(model_class, name='slots', descriptor=None):
"""
Function that adds a description to a model Class.
:param model_class: The model class the descriptor is to be added
to.
:param name: The attribute name the descriptor will be | python | {
"resource": ""
} |
q249915 | PlaceholderDescriptor.create_placeholder_access_object | train | def create_placeholder_access_object(self, instance):
"""
Created objects with placeholder slots as properties.
Each placeholder created for an object will be added to a
`PlaceHolderAccess` object as a set property.
"""
related_model = self.related_model
def get... | python | {
"resource": ""
} |
q249916 | get_users_for_assigned_to | train | def get_users_for_assigned_to():
""" Return a list of users who can be assigned to workflow states """
User | python | {
"resource": ""
} |
q249917 | WorkflowMixinAdmin._get_obj_ct | train | def _get_obj_ct(self, obj):
""" Look up and return object's content type and cache for reuse """
if not hasattr(obj, '_wfct'):
# Use polymorpic content type if available
if hasattr(obj, 'polymorphic_ctype'):
obj._wfct | python | {
"resource": ""
} |
q249918 | WorkflowMixinAdmin.workflow_states_column | train | def workflow_states_column(self, obj):
""" Return text description of workflow states assigned to object """
workflow_states = models.WorkflowState.objects.filter(
content_type=self._get_obj_ct(obj),
| python | {
"resource": ""
} |
q249919 | WorkflowMixinAdmin.created_by_column | train | def created_by_column(self, obj):
""" Return user who first created an item in Django admin """
try:
first_addition_logentry = admin.models.LogEntry.objects.filter(
object_id=obj.pk,
content_type_id=self._get_obj_ct(obj).pk,
| python | {
"resource": ""
} |
q249920 | create_content_instance | train | def create_content_instance(content_plugin_class, page, placeholder_name='main', **kwargs):
"""
Creates a content instance from a content plugin class.
:param content_plugin_class: The class of the content plugin.
:param page: The fluent_page instance to create the content
instance one.
:param ... | python | {
"resource": ""
} |
q249921 | expand_python_version | train | def expand_python_version(version):
"""
Expand Python versions to all identifiers used on PyPI.
>>> expand_python_version('3.5')
['3.5', 'py3', 'py2.py3', 'cp35']
"""
if not re.match(r"^\d\.\d$", version):
return [version]
major, minor = version.split(".")
patterns = [
... | python | {
"resource": ""
} |
q249922 | get_package_hashes | train | def get_package_hashes(
package,
version=None,
algorithm=DEFAULT_ALGORITHM,
python_versions=(),
verbose=False,
include_prereleases=False,
lookup_memory=None,
index_url=DEFAULT_INDEX_URL,
):
"""
Gets the hashes for the given package.
>>> get_package_hashes('hashin')
{
... | python | {
"resource": ""
} |
q249923 | TemplateNameField.formfield | train | def formfield(self, **kwargs):
"""
Get choices from plugins, if necessary.
"""
if self.plugin_class:
self._choices = | python | {
"resource": ""
} |
q249924 | ICEkitURLField.register_model_once | train | def register_model_once(cls, ModelClass, **kwargs):
"""
Tweaked version of `AnyUrlField.register_model` that only registers the
given model after checking that it is not already registered.
"""
if cls._static_registry.get_for_model(ModelClass) is None:
logger.warn("Mo... | python | {
"resource": ""
} |
q249925 | filter_featured_apps | train | def filter_featured_apps(admin_apps, request):
"""
Given a list of apps return a set of pseudo-apps considered featured.
Apps are considered featured if the are defined in the settings
property called `DASHBOARD_FEATURED_APPS` which contains a list of the apps
that are considered to be featured.
... | python | {
"resource": ""
} |
q249926 | _remove_app_models | train | def _remove_app_models(all_apps, models_to_remove):
"""
Remove the model specs in models_to_remove from the models specs in the
apps in all_apps. If an app has no models left, don't include it in the
output.
This has the side-effect that the app view e.g. /admin/app/ may not be
accessible from ... | python | {
"resource": ""
} |
q249927 | filter_sorted_apps | train | def filter_sorted_apps(admin_apps, request):
"""
Filter admin_apps to show the ones in ``DASHBOARD_SORTED_APPS`` first,
and remove them from the subsequent listings.
"""
sorted_apps = []
for orig_app_spec in appsettings.DASHBOARD_SORTED_APPS:
# make a copy that we can write to, to fix ... | python | {
"resource": ""
} |
q249928 | FluentLayoutsMixin.formfield_for_foreignkey | train | def formfield_for_foreignkey(self, db_field, *args, **kwargs):
"""
Update queryset for ``layout`` field.
"""
formfield = super(FluentLayoutsMixin, self).formfield_for_foreignkey(
db_field, *args, **kwargs)
| python | {
"resource": ""
} |
q249929 | FluentLayoutsMixin.get_placeholder_data | train | def get_placeholder_data(self, request, obj):
"""
Get placeholder data from layout.
"""
if not obj or not getattr(obj, 'layout', None):
data = | python | {
"resource": ""
} |
q249930 | ThumbnailAdminMixin.get_thumbnail_source | train | def get_thumbnail_source(self, obj):
"""
Obtains the source image field for the thumbnail.
:param obj: An object with a thumbnail_field defined.
:return: Image field for thumbnail or None if not found.
"""
if hasattr(self, 'thumbnail_field') and self.thumbnail_field:
... | python | {
"resource": ""
} |
q249931 | ThumbnailAdminMixin.preview | train | def preview(self, obj, request=None):
"""
Generate the HTML to display for the image.
:param obj: An object with a thumbnail_field defined.
:return: HTML for image display.
"""
source = self.get_thumbnail_source(obj)
if source:
try:
fr... | python | {
"resource": ""
} |
q249932 | one_instance | train | def one_instance(function=None, key='', timeout=DEFAULT_ONE_INSTANCE_TIMEOUT):
"""
Decorator to enforce only one Celery task execution at a time when multiple
workers are available.
See http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
"""
def _dec(run_func):
def _ca... | python | {
"resource": ""
} |
q249933 | PageIndex.index_queryset | train | def index_queryset(self, using=None):
"""
Index current language translation of published objects.
TODO: Find a way to index all translations of the given model, not just
the current site language's translation.
"""
| python | {
"resource": ""
} |
q249934 | ListingPagePlugin.get_context | train | def get_context(self, request, page, **kwargs):
""" Include in context items to be visible on listing page """
context = super(ListingPagePlugin, self).get_context(
| python | {
"resource": ""
} |
q249935 | ListingPagePlugin.get_view_response | train | def get_view_response(self, request, page, view_func, view_args, view_kwargs):
"""
Render the custom view that was exposed by the extra plugin URL patterns.
This gives | python | {
"resource": ""
} |
q249936 | PublishingAdminForm.clean | train | def clean(self):
"""
Additional clean data checks for path and keys.
These are not cleaned in their respective methods e.g.
`clean_slug` as they depend upon other field data.
:return: Cleaned data.
"""
data = super(PublishingAdminForm, self).clean()
clea... | python | {
"resource": ""
} |
q249937 | _PublishingHelpersMixin.has_publish_permission | train | def has_publish_permission(self, request, obj=None):
"""
Determines if the user has permissions to publish.
:param request: Django request object.
:param obj: The object to determine if the user has
permissions to publish.
:return: Boolean.
"""
# If auto-... | python | {
"resource": ""
} |
q249938 | _PublishingHelpersMixin.has_preview_permission | train | def has_preview_permission(self, request, obj=None):
"""
Return `True` if the user has permissions to preview a publishable
item.
NOTE: this method does not actually change who can or cannot preview
any particular item, just whether to show the preview link. The real
dci... | python | {
"resource": ""
} |
q249939 | _PublishingHelpersMixin.publishing_column | train | def publishing_column(self, obj):
"""
Render publishing-related status icons and view links for display in
the admin.
"""
# TODO Hack to convert polymorphic objects to real instances
if hasattr(obj, 'get_real_instance'):
obj = obj.get_real_instance()
... | python | {
"resource": ""
} |
q249940 | _PublishingHelpersMixin.publish | train | def publish(self, request, qs):
""" Publish bulk action """
# Convert polymorphic queryset instances to real ones if/when necessary
try:
qs = self.model.objects.get_real_instances(qs)
except AttributeError:
| python | {
"resource": ""
} |
q249941 | _PublishingHelpersMixin.unpublish | train | def unpublish(self, request, qs):
""" Unpublish bulk action """
# Convert polymorphic queryset instances to real ones if/when necessary
try:
| python | {
"resource": ""
} |
q249942 | PublishingAdmin.find_first_available_template | train | def find_first_available_template(self, template_name_list):
"""
Given a list of template names, find the first one that actually exists
and is available.
"""
if isinstance(template_name_list, six.string_types):
return template_name_list
| python | {
"resource": ""
} |
q249943 | PublishingAdmin.get_queryset | train | def get_queryset(self, request):
"""
The queryset to use for the administration list page.
:param request: Django request object.
:return: QuerySet.
"""
# TODO Can we remove this hack?
self.request = request
# Obtain the full queryset defined on the regi... | python | {
"resource": ""
} |
q249944 | PublishingAdmin.save_related | train | def save_related(self, request, form, *args, **kwargs):
"""
Send the signal `publishing_post_save_related` when a draft copy is
saved and all its relationships have also been created.
"""
result = super(PublishingAdmin, self) \
.save_related(request, form, *args, **kw... | python | {
"resource": ""
} |
q249945 | PublishingAdmin.render_change_form | train | def render_change_form(self, request, context, add=False, change=False,
form_url='', obj=None):
"""
Provides the context and rendering for the admin change form.
:param request: Django request object.
:param context: The context dictionary to be passed to the ... | python | {
"resource": ""
} |
q249946 | PublishingFluentPagesParentAdminMixin.get_queryset | train | def get_queryset(self, request):
"""
Show only DRAFT Fluent page items in admin.
NOTE: We rely on the `UrlNode.status` to recognise DRAFT versus
PUBLISHED objects, since there the top-level `UrlNode` model and
queryset don't know about ICEKit publishing.
"""
| python | {
"resource": ""
} |
q249947 | Command.find_existing_page | train | def find_existing_page(self, titles_hierarchy):
"""
Find and return existing page matching the given titles hierarchy
"""
# Step backwards through import doc's titles hierarchy with a parent
# count which is the offset from the current level to each ancestor
titles_filter... | python | {
"resource": ""
} |
q249948 | Facet.apply_request_and_page_to_values | train | def apply_request_and_page_to_values(self, request, page=None):
"""
Use the request and page config to figure | python | {
"resource": ""
} |
q249949 | Facet.get_applicable_values | train | def get_applicable_values(self):
"""Return selected values that will affect | python | {
"resource": ""
} |
q249950 | Facet.get_value | train | def get_value(self):
"""Returns the label of the first value"""
try:
return self.get_applicable_values()[0]
except IndexError:
| python | {
"resource": ""
} |
q249951 | Facet.is_default | train | def is_default(self):
"""Return True if no active values, or if the active value is the default"""
| python | {
"resource": ""
} |
q249952 | AbstractBaseModel.save | train | def save(self, *args, **kwargs):
"""
Update ``self.modified``.
"""
self.modified | python | {
"resource": ""
} |
q249953 | publishing_set_update_time | train | def publishing_set_update_time(sender, instance, **kwargs):
""" Update the time modified before saving a publishable object. """
if hasattr(instance, 'publishing_linked'):
# Hack to avoid updating `publishing_modified_at` field when a draft
# publishable item is saved as part of a `publish` oper... | python | {
"resource": ""
} |
q249954 | handle_publishable_m2m_changed | train | def handle_publishable_m2m_changed(
sender, instance, action, reverse, model, pk_set, **kwargs):
"""
Cache related published objects in `pre_clear` so they can be restored in
`post_clear`.
"""
# Do nothing if the target model is not publishable.
if not issubclass(model, PublishingModel):... | python | {
"resource": ""
} |
q249955 | sync_mptt_tree_fields_from_draft_to_published_post_save | train | def sync_mptt_tree_fields_from_draft_to_published_post_save(
sender, instance, **kwargs):
"""
Post save trigger to immediately sync MPTT tree structure field changes
made to draft copies to their corresponding published copy.
"""
mptt_opts | python | {
"resource": ""
} |
q249956 | sync_mptt_tree_fields_from_draft_to_published | train | def sync_mptt_tree_fields_from_draft_to_published(
draft_copy, dry_run=False, force_update_cached_urls=False):
"""
Sync tree structure changes from a draft publishable object to its
published copy, and updates the published copy's Fluent cached URLs when
necessary. Or simulates doing this if ``d... | python | {
"resource": ""
} |
q249957 | create_can_publish_and_can_republish_permissions | train | def create_can_publish_and_can_republish_permissions(sender, **kwargs):
"""
Add `can_publish` and `ca_nrepublish` permissions for each publishable
model in the system.
"""
for model in sender.get_models():
if not issubclass(model, PublishingModel):
continue
content_type =... | python | {
"resource": ""
} |
q249958 | maybe_automatically_publish_drafts_on_save | train | def maybe_automatically_publish_drafts_on_save(sender, instance, **kwargs):
"""
If automatic publishing is enabled, immediately publish a draft copy after
it has been saved.
"""
# Skip processing if auto-publishing is not enabled
if not is_automatic_publishing_enabled(sender):
return
... | python | {
"resource": ""
} |
q249959 | PublishingModel.has_been_published | train | def has_been_published(self):
"""
Return True if the item is either published itself, or has an
associated published copy.
This is in contrast to ``is_published`` which only returns True if
the specific object is a published copy, and | python | {
"resource": ""
} |
q249960 | PublishingModel.get_draft | train | def get_draft(self):
"""
Return self if this object is a draft, otherwise return the draft
copy of a published item.
"""
if self.is_draft:
return self
elif self.is_published:
draft = self.publishing_draft
# Previously the reverse relati... | python | {
"resource": ""
} |
q249961 | PublishingModel.get_published | train | def get_published(self):
"""
Return self is this object is published, otherwise return the
published copy of a draft item. If this object is a draft with
no published copy it will return ``None``.
"""
if self.is_published:
| python | {
"resource": ""
} |
q249962 | PublishingModel.get_published_or_draft | train | def get_published_or_draft(self):
"""
Return the published item, if it exists, otherwise, for privileged
users, return the draft version.
"""
if self.is_published:
return self
elif self.publishing_linked_id:
| python | {
"resource": ""
} |
q249963 | PublishingModel.publish | train | def publish(self):
"""
Publishes the object.
The decorator `assert_draft` makes sure that you cannot publish
a published object.
:param self: The object to tbe published.
:return: The published object.
"""
if self.is_draft:
# If the object has... | python | {
"resource": ""
} |
q249964 | PublishingModel.unpublish | train | def unpublish(self):
"""
Un-publish the current object.
"""
if self.is_draft and self.publishing_linked:
publishing_signals.publishing_pre_unpublish.send(
sender=type(self), instance=self)
# Unlink draft and published copies then delete published.
... | python | {
"resource": ""
} |
q249965 | PublishingModel.publishing_prepare_published_copy | train | def publishing_prepare_published_copy(self, draft_obj):
""" Prepare published copy of draft prior to saving it """
# We call super here, somewhat perversely, to ensure this method | python | {
"resource": ""
} |
q249966 | PublishingModel.clone_fluent_placeholders_and_content_items | train | def clone_fluent_placeholders_and_content_items(self, dst_obj):
"""
Clone each `Placeholder` and its `ContentItem`s.
:param self: The object for which the placeholders are
to be cloned from.
:param dst_obj: The object which the cloned placeholders
are to be related.
... | python | {
"resource": ""
} |
q249967 | Command.handle_noargs | train | def handle_noargs(self, **options):
"""
By default this function runs on all objects.
As we are using a publishing system it should only update draft
objects which can be modified in the tree structure.
Once published the tree preferences should remain the same to
ensur... | python | {
"resource": ""
} |
q249968 | AbstractLayoutIndex.full_prepare | train | def full_prepare(self, obj):
"""
Make django_ct equal to the type of get_model, to make polymorphic
children show up in results.
"""
| python | {
"resource": ""
} |
q249969 | grammatical_join | train | def grammatical_join(l, initial_joins=", ", final_join=" and "):
"""
Display a list of items nicely, with a different string before the final
item. Useful for using lists in sentences.
>>> grammatical_join(['apples', 'pears', 'bananas'])
'apples, pears and bananas'
>>> grammatical_join(['apple... | python | {
"resource": ""
} |
q249970 | update_GET | train | def update_GET(parser, token):
"""
``update_GET`` allows you to substitute parameters into the current request's
GET parameters. This is useful for updating search filters, page numbers,
without losing the current set.
For example, the template fragment::
<a href="?{% update_GET 'attr1' +=... | python | {
"resource": ""
} |
q249971 | oembed | train | def oembed(url, params=""):
"""
Render an OEmbed-compatible link as an embedded item.
:param url: A URL of an OEmbed provider.
:return: The OEMbed ``<embed>`` code.
"""
# Note: this method isn't currently very efficient - the data isn't
# cached or stored.
kwargs = dict(urlparse.parse_... | python | {
"resource": ""
} |
q249972 | admin_link | train | def admin_link(obj):
"""
Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj:... | python | {
"resource": ""
} |
q249973 | admin_url | train | def admin_url(obj):
"""
Returns the admin URL of the object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_url }}
renders as::
/admin/foo/123
:param obj: | python | {
"resource": ""
} |
q249974 | sharedcontent_exists | train | def sharedcontent_exists(slug):
"""
Return `True` if shared content with the given slug name exists.
This filter makes it possible to conditionally include shared content with
surrounding markup only when the shared content item actually exits, and
avoid outputting the surrounding markup when it do... | python | {
"resource": ""
} |
q249975 | RawIdPreviewAdminMixin.render_field_error | train | def render_field_error(self, obj_id, obj, exception, request):
"""
Default rendering for items in field where the the usual rendering
method raised an exception.
"""
if obj is None:
| python | {
"resource": ""
} |
q249976 | RawIdPreviewAdminMixin.render_field_previews | train | def render_field_previews(self, id_and_obj_list, admin, request, field_name):
"""
Override this to customise the preview representation of all objects.
"""
obj_preview_list = []
for obj_id, obj in id_and_obj_list:
try:
# Handle invalid IDs
... | python | {
"resource": ""
} |
q249977 | AbstractLinkItem.get_item | train | def get_item(self):
"If the item is publishable, get the visible version"
if hasattr(self, 'get_draft'):
draft = self.get_draft()
else:
draft = self
if not hasattr(self, '_item_cache'):
try:
| python | {
"resource": ""
} |
q249978 | LinkPlugin.render | train | def render(self, request, instance, **kwargs):
"""
Only render the plugin if the item can be shown to | python | {
"resource": ""
} |
q249979 | ModelSubSerializer.get_fields | train | def get_fields(self):
"""
Convert default field names for this sub-serializer into versions where
the field name has the prefix removed, but each field object knows the
real model field name by setting the field's `source` attribute.
"""
prefix = getattr(self.Meta, 'sourc... | python | {
"resource": ""
} |
q249980 | WritableSerializerHelperMixin._populate_validated_data_with_sub_field_data | train | def _populate_validated_data_with_sub_field_data(self, validated_data):
"""
Move field data nested in `ModelSubSerializer` fields back into the
overall validated data dict.
"""
for fieldname, field in self.get_fields().items():
if | python | {
"resource": ""
} |
q249981 | WritableSerializerHelperMixin._prepare_related_single_or_m2m_relations | train | def _prepare_related_single_or_m2m_relations(self, validated_data):
"""
Handle writing to nested related model fields for both single and
many-to-many relationships.
For single relationships, any existing or new instance resulting from
the provided data is set back into the prov... | python | {
"resource": ""
} |
q249982 | WritableSerializerHelperMixin._get_or_update_or_create_related_instance | train | def _get_or_update_or_create_related_instance(
self, ModelClass, fieldname, field_data
):
"""
Handle lookup, update, or creation of related instances based on the
field data provided and the field's `writable_related_fields` settings
as defined on the serializer's `Meta`.... | python | {
"resource": ""
} |
q249983 | WritableSerializerHelperMixin._write_related_m2m_relations | train | def _write_related_m2m_relations(self, obj, many_to_many_relationships):
"""
For the given `many_to_many_relationships` dict mapping field names to
a list of object instances, apply the instance listing to the `obj`s
named many-to-many relationship field.
"""
for | python | {
"resource": ""
} |
q249984 | FileSystemLayoutsPlugin.get_choices | train | def get_choices(self):
"""
Return a list of choices for source files found in configured layout
template directories.
"""
choices = []
for label_prefix, templates_dir, template_name_prefix in \
appsettings.LAYOUT_TEMPLATES:
source_dir = os.path... | python | {
"resource": ""
} |
q249985 | environment | train | def environment(**options):
"""
Add ``static`` and ``url`` functions to the ``environment`` context
processor and return as a Jinja2 ``Environment`` object.
"""
env = Environment(**options)
env.globals.update({ | python | {
"resource": ""
} |
q249986 | update_site | train | def update_site(sender, **kwargs):
"""
Update `Site` object matching `SITE_ID` setting with `SITE_DOMAIN` and
`SITE_PORT` settings.
"""
Site = apps.get_model('sites', 'Site')
domain = settings.SITE_DOMAIN
if settings.SITE_PORT:
domain += ':%s' % settings.SITE_PORT
Site.objects.up... | python | {
"resource": ""
} |
q249987 | _format_with_same_year | train | def _format_with_same_year(format_specifier):
"""
Return a version of `format_specifier` that renders a date
assuming it has the same year as another date. Usually this means ommitting
the year.
This can be overridden by specifying a format that has `_SAME_YEAR` appended
to the name in the ... | python | {
"resource": ""
} |
q249988 | _format_with_same_year_and_month | train | def _format_with_same_year_and_month(format_specifier):
"""
Return a version of `format_specifier` that renders a date
assuming it has the same year and month as another date. Usually this
means ommitting the year and month.
This can be overridden by specifying a format that has
`_SAME_YEAR_S... | python | {
"resource": ""
} |
q249989 | LayoutAdmin._get_ctypes | train | def _get_ctypes(self):
"""
Returns all related objects for this model.
"""
ctypes = []
for related_object in self.model._meta.get_all_related_objects():
model = getattr(related_object, 'related_model', related_object.model)
ctypes.append(ContentType.object... | python | {
"resource": ""
} |
q249990 | LayoutAdmin.placeholder_data_view | train | def placeholder_data_view(self, request, id):
"""
Return placeholder data for the given layout's template.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
try:
layout = models.Layout.objects.get(pk=id)
except models.Layout.DoesNotExist:
... | python | {
"resource": ""
} |
q249991 | LayoutAdmin.get_urls | train | def get_urls(self):
"""
Add ``layout_placeholder_data`` URL.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
urls = super(LayoutAdmin, self).get_urls()
| python | {
"resource": ""
} |
q249992 | RecurrenceRuleWidget.decompress | train | def decompress(self, value):
"""
Return the primary key value for the ``Select`` widget if the given
recurrence rule exists in the queryset.
"""
if value:
try:
| python | {
"resource": ""
} |
q249993 | RecurrenceRuleField._set_queryset | train | def _set_queryset(self, queryset):
"""
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
"""
| python | {
"resource": ""
} |
q249994 | EventContentListingAdminForm.filter_content_types | train | def filter_content_types(self, content_type_qs):
""" Filter the content types selectable to only event subclasses """
valid_ct_ids = []
for ct in content_type_qs:
model = ct.model_class()
| python | {
"resource": ""
} |
q249995 | describe_page_numbers | train | def describe_page_numbers(current_page, total_count, per_page, page_numbers_at_ends=3, pages_numbers_around_current=3):
"""
Produces a description of how to display a paginated list's page numbers. Rather than just
spitting out a list of every page available, the page numbers returned will be trimmed
to... | python | {
"resource": ""
} |
q249996 | render_stats | train | def render_stats(stats, sort, format):
"""
Returns a StringIO containing the formatted statistics from _statsfile_.
_sort_ is a list of fields to sort by.
_format_ is the | python | {
"resource": ""
} |
q249997 | render_queries | train | def render_queries(queries, sort):
"""
Returns a StringIO containing the formatted SQL queries.
_sort_ is a field to sort by.
"""
output = StringIO()
if sort == 'order':
print >>output, " time query"
for query in queries:
print >>output, " %8s %s" % (query["time"... | python | {
"resource": ""
} |
q249998 | unpickle_stats | train | def unpickle_stats(stats):
"""Unpickle a pstats.Stats | python | {
"resource": ""
} |
q249999 | display_stats | train | def display_stats(request, stats, queries):
"""
Generate a HttpResponse of functions for a profiling run.
_stats_ should contain a pstats.Stats of a hotshot session.
_queries_ should contain a list of SQL queries.
"""
sort = [
request.REQUEST.get('sort_first', 'time'),
request.R... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.